I have a simple Angular 15 app and ViewChildren is not working, even with a setTimeout() within ngAfterViewInit, in which I subscribe to changes of the ViewChildren instance:
app.component.html
<app-simple
*ngFor="let simpleStr of testStrings"
[str]="simpleStr"></app-simple>
app.component.ts
import { AfterViewInit, Component, QueryList, ViewChildren } from '@angular/core';
import { SimpleComponent } from './simple/simple.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit {
@ViewChildren(SimpleComponent) simpleChildren?: QueryList<SimpleComponent>;
testStrings: string[] = [
"simple one",
"simple two",
"simple three"
];
ngAfterViewInit(): void {
setTimeout(() => {
this.simpleChildren?.changes.subscribe({
next: (data) => {
if (this.simpleChildren && this.simpleChildren.length) {
this.simpleChildren.forEach((simple: any) => {
if (simple) {
console.log(simple.str);
simple.str.simpleFunction();
}
});
}
},
error: (err) => {
console.log('Error with view children');
}
});
}, 2000);
}
}
simple.component.html
<p>{{str}}</p>
simple.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-simple',
templateUrl: './simple.component.html'
})
export class SimpleComponent {
@Input() str: string = "";
simpleFunction() {
console.log('simpleFunction called for: ', this.str);
}
}