Reputation: 5149
I'm trying to get an better understanding of Angular 2. I am receiving a list of people from endpoint and periodically the list changes. People Component:
@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[];
}
Attendees Component:
@Component({
selector: 'attendees',
templateUrl: '<span>{{attendees}}</span>',
})
export class AttendeesComponent implements OnInit {
constructor() { }
ngOnInit() {}
}
I've looked for a way to change automatically update my template whenever the value of input changes. I have yet to find a way of doing this. I've thought about doing a setTimout, but there has to be more efficient way. Can someone assist me or point me in the right direction? I need the ngFor to update dynamically.
Upvotes: 0
Views: 1845
Reputation: 2702
For your purpose Angular provides you two way binding
where any further changes to the model gets refelected to the template automatically and vice-versa.
Example:
List Component
@Component({
selector: 'my-comp',
template: `<ul>
<li *ngFor="let item of people">{{item}}</li>
</ul>`
})
export class MyComp {
@Input() people: string[];
}
Usage
@Component({
selector: 'main-comp',
template: '<my-comp [people]="list"></my-comp>'
})
export class MainComp {
private list: string[];
ngOnInit() {
this.list= ['male', 'female'];
}
}
Upvotes: 0
Reputation: 222582
You do not have to do anything manually inorder to track changes, angular2 framework automatically does that , make sure you pass the people as a input to your child component,
Assuming mycomponent is your child component and people
is the input
<mycomponent [people]="peopleValue" .... ></mycomponent>
Upvotes: 0
Reputation: 4358
The question is how do you pass people
to your component.
Assuming that your component is my-people
then you should pass people
as following
<my-people [people]="peopleValue" .... ></my-people>
Upvotes: 2