简体   繁体   English

Angular6 @ViewChildren使用标识符

[英]Angular6 @ViewChildren using identifier

I have created a directive with a selected pyb-button-group that uses @ViewChildren , which is declared like this: 我创建了一个使用选定的pyb-button-group的指令,该指令使用@ViewChildren ,其声明如下:

@ViewChildren('header', { read: ElementRef }) headers: QueryList<ElementRef>

My html template looks a bit like this: 我的html模板看起来像这样:

<div class="container" *ngIf="categories">
  <div class="row" pyb-button-group>
    <div class="col-md-4 col-6" *ngFor="let category of categories">
      <a class="btn-choice" [routerLink]="['/' + category.id]">
        <div class="header" #header>
          <span class="title">{{ category.name }}</span>
        </div>
      </a>
    </div>
  </div>
</div>

So I have a method that fires using ngAfterViewInit like this: 所以我有一种使用ngAfterViewInit触发的方法,如下所示:

ngAfterViewInit() {
  console.log(this.headers);
}

and it returns undefined .... 并返回undefined ...。

Am I doing something wrong? 难道我做错了什么?

it should be something like: 它应该是这样的:

@ContentChildren('header', { read: ElementRef }) headers: QueryList<ElementRef>

ngAfterViewInit(){
 this.headers.toArray().forEach(el => {
      console.log(el);
  });
 }
}

DEMO DEMO

It will work with ViewChildern also, 它也可以与ViewChildern一起使用,

export class AppComponent {

  @ViewChildren('header', { read: ElementRef }) headers: QueryList<ElementRef>
  categories: {
    name: string
  }[] = [];

  ngOnInit() {
    this.categories = [];
    this.categories.push({ name: "Test" }, { name: "Test2" });
  }

  ngAfterViewInit() {
    console.log(this.headers);
    this.headers.toArray().forEach(header => console.log(header));
  }
}

Here is a working sample, https://stackblitz.com/edit/angular-jdkdro 这是一个工作示例, https://stackblitz.com/edit/angular-jdkdro

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM