iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 20
0
Modern Web

Angular初期筆記系列 第 20

DAY20-Angular6之實現子上父

  • 分享至 

  • twitterImage
  •  

先備知識

EventEmitter(中文:事件發射器)
發射一個同步或非同步的自訂事件在 directives 和 components ,並註冊處理這些事件,用在訂閱成一個實體
https://angular.io/api/core/EventEmitter

實作父值加 1

app\test1\test1.component.html (子)
-----
<button (click)="addValue($event.target.value)" value="1">我要加一</button>
app\test1\test1.component.ts (子)
-----
export class Test1Component implements OnInit {
    @Output() addEvent = new EventEmitter();

    constructor() { }

    ngOnInit() {
    }

    addValue(value) {
        value = Number(value);
        this.addEvent.emit(value);
    }
}

新增一個 EventEmitter() 並用 @Output() 裝飾
在 addValue function 內將 addEvent 發射出去並帶 值

app\app.component.html (父)
-----
<app-test1 #haha (addEvent)="add($event)"></app-test1>
{{totalValue}}

綁定 test1.component.ts 的 addEvent 發射事件,當接收到 addEvent 的 emit ,就觸發 add 事件
$event 接收到的就是 子 射出來 值

使用已經傳遞給 output event 處理過 的 $event 參數 ,就可以訪問到 event object
https://angular.io/api/core/EventEmitter#usage-notes

app\app.component.ts (父)
------
export class AppComponent implements OnInit {
    totalValue = 0;

    ngOnInit() {
    }

    add(value) {
        this.totalValue += value;
    }
}

顯示
https://ithelp.ithome.com.tw/upload/images/20181030/20107754XKLVYA7Vfa.png

點擊「我要加一」
https://ithelp.ithome.com.tw/upload/images/20181030/20107754p9nlRc43zi.png

流程就是
子 發射事件→父 接收,並執行對應事件


上一篇
DAY19-Angular6之實現父到子傳值
下一篇
DAY21-Angular6之pipe
系列文
Angular初期筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言