Angular访问ng容器中的子组件列表



我有以下模板

<ng-container *ngFor="let object of objects">
<child-component [input]="object "> </child-component>
<input type="number" id="numvalue">
</<ng-container>

有没有任何方法可以访问我的子组件以及输入值。我尝试使用ViewContainerRef,但似乎无法访问子组件

在循环AfterViewInit中,我们查询用#child标记的所有子级,然后查询该子级的console.log()属性input(请检查控制台(。

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
@ViewChildren('child') childs: QueryList<ElementRef>;
objects: string[] = ['first', 'second', 'thrid'];
constructor() {}
ngAfterViewInit() {
this.childs.forEach((child: any) => {
if (child.input) {
console.log(child.input);
}
});
}
}
<ng-container *ngFor="let object of objects">
<input type="number" id="numvalue"/> {{object}}
<app-child-hello [input]="object" #child></app-child-hello>
</ng-container>

儿童

@Component({
selector: 'app-child-hello',
template: `<h1>Hello {{input}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
@Input() input: string;
}

以下是一个工作示例:https://stackblitz.com/edit/angular-ivy-xh3kil?file=src%2Fapp%2Fapp.component.ts

最新更新