I currently have two types of Components, and ParentComponent that holds an array of ChildComponents.
Something like this:
@Component({
...
})
export class ParentComponent {
children: ChildComponent[] = [];
// methods that use properties in children
}
and then the ChildComponent could look something like this:
@Component({
...
})
export class ChildComponent {
@Input() title: string = "Default Title";
changeTitle() {
this.title = "New Title";
}
}
How would I go about writing a template that could *ngFor
over each item in children
and display the appropriate ChildComponent? The way I am currently doing it is making title
an input in ChildComponent and doing something like this in the ParentComponent template:
<child-component *ngFor="let child of children" [title]="child.title"><child-component>
This works totally fine for setting info, but not for getting updated info in ParentComponent when title
in a ChildComponent changes. See this Plunker for an example. If you click the "Add Child" button, it will add a new ChildComponent to children
and use the title "Test", correctly overriding "Default Title". Now try clicking the "Change Title" button for any of the ChildComponents and then click "Print Titles" at the bottom.
As you can see, the original "Test" titles are still being read because the ChildComponents being displayed are not actually the ones stored in children
. Is there a way that I could directly display the ChildComponents instead of creating new ones?