angular 組件間的交流(1)--@Output 和@Input

總的來說,Input 用來進行屬性綁定,將父組件的屬性傳給子組件,即有數據傳進組件;Output 用來在事件綁定時,子組件將事件傳給父組件進行處理,既有數據傳出組件;如圖:

@Output()

先來看串代碼:app-child.component.ts

import {Component, Input, EventEmitter, Output  } from '@angular/core';
@Component ({
    selector: 'app-child',
    template: `<button class="btn btn-primary" (click)="handleclick()">Click me</button>`
})
export class AppChildComponent {
    handleclick () {
        console.log('hello,Child');
    }
}

在這個子組件模板中,有個按鈕,綁定了 click 事件;將這個模板放進根模塊 AppComponent.ts 中爲:

import {Component  } from "@angular/core";
@Component({
  selector: 'app-root',
  template: `<app-child></app-child>`
})
export class AppComponent implements OnInit{
  ngOnInit(){
  }
}

當把 <app-child></app-child> 放進 AppComponent 中,組件之間產生了父子關係,AppComponent 爲父組件;當點擊按鈕時,console 會打印出 "hello,child",這是一個很常見的事件綁定。現在我們想想:如果想在子組件按鈕點擊事件中執行父組件的功能,我們該怎麼做呢? 要做到這一點,需要將事件從子組件中發送到父組件,於是,我們引入 'angular/core' 模塊中的 Output 和事件發射器 EventEmitter;現在我們發出事件,並且將事件傳參;

import {Component, EventEmitter, Output  } from '@angular/core';
@Component ({
    selector: 'app-child',
    template: `<button class="btn btn-primary" (click)="valueChanged()">Click me</button>`
})
export class AppChildComponent {
    @Output() valueChange = new EventEmitter();
    Counter = 0;
    valueChanged() {
        this.Counter = this.Counter + 1;
        this.valueChange.emit(this.Counter);
    }
}

我們做了如下操作:

  • 定義 Counter,將其作爲參數傳遞給所發出的事件的參數;
  • 創建了 EventEmitter 實例,他將會被傳遞到父組件的按鈕點擊事件上;
  • 創建了 valueChanged 方法,用於處理按鈕點擊事件; 父組件 appComponent.ts 的代碼爲:
import {Component  } from "@angular/core";
@Component({
  selector: 'app-root',
  template: `<app-child (valueChange)="displayCounter($event)"></app-child>`
})
export class AppComponent implements OnInit{
  ngOnInit(){
  }
 displayCounter(count){
 consoloe.log(count);
 }
}

在父組件的模板的事件綁定中,注意綁定的是 valueChange,它是從子組件傳遞過來的事件發射器實例;這裏定義了 displayCounter() 函數,在子組件按鈕點擊事件觸發的時候,父組件的這個功能也會執行,打印出 counter 的值; 以上,就實現了在子組件按鈕點擊事件發生後,父組件的功能也會執行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章