我制作了一个自定义组件,并从父组件中引用它,如下所示:
<div *ngFor="let item of list | async">
<child-component></child-component>
</div>
在父组件中,&#34; list&#34;定义为:
public list: Observable<any[]>;
当我在&#34;列表&#34;中添加内容时通过将其添加到列表正在观察的事物中,并将新的子组件添加到DOM中。
this.list.push(new-object);
// this adds a new child-component to the DOM and
// returns a value that I need to add into the new object I just pushed
我的问题是: 如何获取对最后添加到&#34;列表&#34;创建的组件的引用?在推送之后,我可以使用&#34; this.list.push&#34;的响应中的信息进一步修改该项目?
答案 0 :(得分:0)
有几种方法
您可以设置属性或属性以指示您想要获取的元素
<div *ngFor="let item of list; let last=last">
<child-component [item]="item" [attr.last]="last ? true : null" [isLast]="last"></child-component>
</div>
您可以获取元素或组件
@ViewChildren(ChildComponent) children: QueryList<ChildComponent>;
@ViewChildren(ChildComponent, {read: ElementRef}) childElements: QueryList<ElementRef>;
您可以查询所有这些元素,只获取最后一个元素或获取具有特定属性或属性集的元素
ngAfterViewInit() {
this.children.changes.subscribe(val => {
console.log('all children: ', this.children.toArray());
console.log('last children: ', this.children.toArray()[this.children.toArray().length - 1]);
console.log('child with last attribute: ', this.children.toArray().find(child => child.elementRef.nativeElement.getAttribute('last') != null));
console.log('child with isLast property set: ', this.children.toArray().find(child => child.isLast);
console.log('all childElements: ', this.childElements.toArray());
console.log(this.childElements.toArray().find(child => child.nativeElement.getAttribute('last') != null)); // <<< doesn't work, don't know why
});
}