Using a `@ViewChild` in a template binding throws an `ExpressionChangedAfterItHasBeenCheckedError`

58 Views Asked by At

Repro: https://stackblitz.com/edit/angular-rjxytd?file=src%2Fmain.ts

I'm trying to use a dynamic @ViewChild field in an *ngIf binding, but the mere act of mentioning it in a template throws ExpressionChangedAfterItHasBeenCheckedError, for example:

@Component({
  selector: 'child',
  standalone: true,
  template: '',
})
class Child {
  id = 'child';
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [Child, CommonModule],
  template: `    
    <child></child>
    <h1 *ngIf='child'>Hello!</h1>    
  `,
})
export class App {
  @ViewChild(Child) child: Child | undefined;
}

0

There are 0 best solutions below