1. 程式人生 > >【Angular2】元件互動

【Angular2】元件互動

前言

在Angular開發中,我們經常會涉及到元件之間的互動,比如會引用自己部門開發的元件
有時候,我們需要向引用的元件裡面繫結一些資料,或者我們需要引用的子元件輸出一些資料
這時,我們就需要處理好元件之間的互動

元件互動的關鍵程式碼

父元件繫結資料到子元件

子元件

  <h3>{{hero.name}} says:</h3>
  @Input() hero: Hero;

父元件

<hero-child  [hero]="myhero" ></hero-child>
myhero = “Mr.IQ”;

這裡子元件的@Input表示它需要hero這個實體,之後父元件引入子元件的時候,就得在子元件標籤內寫入hero,同時在自己的元件內為hero賦值就實現了父元件資料繫結到子元件

父元件監聽子元件的事件

子元件

<button (click)="vote(true)" >Agree</button>
@Output() onVoted = new EventEmitter<boolean>();
vote(agreed: boolean) { this.onVoted.emit(agreed);}

父元件

<my-voter (myonVoted)="onVoted($event)"></my-voter>
myonVoted(agreed: boolean) { agreed ? this.agreed++ : this
.disagreed++; }

子元件的@Output表示它會用onVoted方法向父元件傳遞一個boolean值,父元件引入子元件之後,通過把子元件的方法繫結到自己的方法上,就可以達到監聽子元件的效果

setter截聽輸入屬性值的變化

子元件

<h3>"{{name}}"</h3>
private _name = '';
@Input()
set name(name: string) { this._name = (name && name.trim()) || '<no name set>'; }
get name(): string
{ return this._name; }

父元件

<name-child  [name]="myname"></name-child>

父元件引用子元件之後,向子元件繫結資料,子元件通過set,get對父元件傳過來的資料進行修改顯示

父元件與子元件通過本地變數互動

子元件

seconds = 11;
stop()  { this.message = `Holding at T-${this.seconds} seconds`;   }

父元件

<button (click)="timer.stop()">Stop</button>
<div class="seconds">{{timer.seconds}}</div>
<countdown-timer #timer></countdown-timer>

子元件定義了變數和方法,父元件引用子元件標籤之後,通過在標籤建立本地變數來代表子元件,然後通過變數就可以實現訪問子元件的變數和方法

小結

元件互動是經常用到的知識,需要熟練掌握
還有其它互動方式,比如生命週期、服務,遇到了可以繼續深入研究