r3plica
r3plica

Reputation: 13387

Angular6 @ViewChildren using identifier

I have created a directive with a selected pyb-button-group that uses @ViewChildren, which is declared like this:

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

My html template looks a bit like this:

<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() {
  console.log(this.headers);
}

and it returns undefined....

Am I doing something wrong?

Upvotes: 1

Views: 806

Answers (2)

Lia
Lia

Reputation: 11982

it should be something like:

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

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

DEMO

Upvotes: 1

Sreekumar P
Sreekumar P

Reputation: 6050

It will work with ViewChildern also,

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

Upvotes: 0

Related Questions