【发布时间】:2017-04-02 16:10:01
【问题描述】:
我是 Angular 的新手,遇到了一个子组件上的构造函数被调用两次的问题,第二次调用它是清除第一次设置的属性。
这是父组件:
@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);
}
}
并且在模板中引用了子组件:
<child-items [parentItemId]="parentItemId">Loading...</<child-items>
这是子组件:
@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!");
}
}
}
最后是子组件模板:
<tr *ngFor="let item of items | async">
<td>...</td>
</tr>
子组件构造函数被调用了两次,第二次调用时 parentItemId 被设置为 null 并且 items 属性被清除。如果我硬编码 parentId 而不是使用输入,则数据会被正确接收并显示在模板中,但使用输入值,模板不会显示任何结果。
我创建了一个 plunker,它在此处显示相同的行为:http://embed.plnkr.co/xaJtfNgbWCUPap2RCJUA/
【问题讨论】:
-
<child-items [parentItemId]="parentItemId">Loading...</<child-items>是</<故意这样做的吗?
标签: javascript angular html typescript angular-components