[英]Updating ngFor when Input value changes
我試圖更好地了解Angular2。我收到來自端點的人員列表,並且該列表會定期更改。 人員組成:
@Component({
selector: 'people-display',
template: <ol class="people-list">
<li *ngFor="let person of people">
<attendees [people]="peopleValue"></attendees>
</li>
</ol>
})
export class PeopleComponent implements OnChanges {
@Input() people: string[];
}
與會者組成:
@Component({
selector: 'attendees',
templateUrl: '<span>{{attendees}}</span>',
})
export class AttendeesComponent implements OnInit {
constructor() { }
ngOnInit() {}
}
我一直在尋找一種方法,只要輸入值發生變化,它就會自動更新模板。 我還沒有找到一種方法。 我曾考慮過進行setTimout,但是必須有一種更有效的方法。 有人可以協助我或為我指明正確的方向嗎? 我需要ngFor動態更新。
問題是如何將people
傳遞到您的組件。
假設您的組成部分是my-people
那么您應該按照以下方式通過people
<my-people [people]="peopleValue" .... ></my-people>
您無需手動執行任何操作即可跟蹤更改,angular2框架會自動執行此操作,確保將人員作為輸入傳遞給子組件,
假設mycomponent是您的子組件,而people
是輸入
<mycomponent [people]="peopleValue" .... ></mycomponent>
出於您的目的,Angular為您提供了two way binding
,其中對模型的任何進一步更改將自動重新選擇到模板,反之亦然。
例:
列表組件
@Component({
selector: 'my-comp',
template: `<ul>
<li *ngFor="let item of people">{{item}}</li>
</ul>`
})
export class MyComp {
@Input() people: string[];
}
用法
@Component({
selector: 'main-comp',
template: '<my-comp [people]="list"></my-comp>'
})
export class MainComp {
private list: string[];
ngOnInit() {
this.list= ['male', 'female'];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.