I am new to Angular, and I ran into a problem when the constructor on the child component is called twice, and the second time it is called, it is cleaning the properties set for the first time.
This is the parent component:
@Component({
selector: 'parent-item',
templateUrl: '...',
providers: [ItemService]
})
export class ParentItemComponent {
public parentItemId;
public model: ParentItem;
constructor(itemService: ItemService, elm: ElementRef) {
this.parentItemId = elm.nativeElement.getAttribute('parentItemId');
itemService.getParentItem(this.parentItemId).subscribe(data => this.model = data);
}
}
And in the template link to the child component:
<child-items [parentItemId]="parentItemId">Loading...</<child-items>
This is a child component:
@Component({
selector: 'child-items',
templateUrl: '...',
providers: [ItemService]
})
export class ChildItemsComponent {
@Input() public parentItemId: number;
public items: Observable<ChildItem[]>;
constructor(private itemService: ItemService) {
console.log("constructor");
}
ngOnInit() {
if (this.parentItemId) {
this.items = this.itemService.getChildItems(this.parentItemId);
}
else {
console.log("Parent Id not set!");
}
}
}
And finally, the template of the child component:
<tr *ngFor="let item of items | async">
<td>...</td>
</tr>
The constructor of the child components is called twice, and the second time its name parentItemId is null and the items property is cleared. If I rigidly bind parentId instead of using input, the data is correctly accepted and displayed in the template, but using the input value, the template does not show results.
, : http://embed.plnkr.co/xaJtfNgbWCUPap2RCJUA/