簡體   English   中英

Angular 訪問 ng-container 中的子組件列表

[英]Angular accessing a list of child components in a ng-container

我有以下模板

<ng-container *ngFor="let object of objects">
   <child-component [input]="object "> </child-component>
   <input type="number" id="numvalue">
</<ng-container>

有什么方法可以在輸入值旁邊訪問我的子組件。 我嘗試使用 ViewContainerRef 但似乎無法訪問子組件

在循環AfterViewInit中,我們查詢所有標有#child的子節點,然后我們input該子節點的console.log()屬性(請檢查控制台)。

@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>

孩子

@Component({
  selector: 'app-child-hello',
  template: `<h1>Hello {{input}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() input: string;
}

這是一個工作示例: https://stackblitz.com/edit/angular-ivy-xh3kil?file=src%2Fapp%2Fapp.component.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM