0

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);
    }
}
Greg Lafrance
  • 768
  • 1
  • 7
  • 18
  • This seems like an important issue, as it seems to indicate that angular ViewChildren doesn't work at all, at least in this supposedly common scenario. So no one has the knowledge to provide guidance? – Greg Lafrance Feb 08 '23 at 18:16

0 Answers0