Issue
I have the following template
<ng-container *ngFor="let object of objects">
<child-component [input]="object "> </child-component>
<input type="number" id="numvalue">
</<ng-container>
Is there any way to access my child components along side the input values. I tried using ViewContainerRef but cant seems to access child components
Solution
In cycle AfterViewInit we query for all of our children marked with #child and we then console.log() property input of that child (please check console).
@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>
The child
@Component({
selector: 'app-child-hello',
template: `<h1>Hello {{input}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() input: string;
}
Here is a working example: https://stackblitz.com/edit/angular-ivy-xh3kil?file=src%2Fapp%2Fapp.component.ts
Answered By - Joosep.P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.