Home > Enterprise >  Angular accessing a list of child components in a ng-container
Angular accessing a list of child components in a ng-container

Time:02-04

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

CodePudding user response:

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/app/app.component.ts

  •  Tags:  
  • Related