angular6 組件間的交流方式(1)--@Output 和@Input

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

@Output()

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

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;如今咱們發出事件,而且將事件傳參;this

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);
    }
}

咱們作了以下操做:code

  • 定義 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 的值; 以上,就實現了在子組件按鈕點擊事件發生後,父組件的功能也會執行。component

相關文章
相關標籤/搜索