Home > Mobile >  Query buttons present inside ng-content in angular
Query buttons present inside ng-content in angular

Time:11-30

I want to query buttons present inside ng-content.

Slackblitz

html:

 <div appItem>
    <ng-content></ng-content>
  </div>

ts:

ViewChildren(ItemDirective) buttons: QueryList<ItemDirective>;

  constructor() {}
  ngAfterContentInit(): void {
    console.log(this.buttons);
  }
  ngAfterViewInit(): void {
    console.log(this.buttons);
  }

Directive:

import { Directive } from '@angular/core';

@Directive({
  selector: '[appItem]'
})
export class ItemDirective {

  constructor() { }

}

Query list does not provide the list of buttons. Other things are present in it. How can I get the list of buttons in queryList?

I have tried ViewChildren and ContentChildren (both)

CodePudding user response:

You should put the appItem in the button element itself.

<button appItem>Button X</button>

Forked Link

CodePudding user response:

use ContentChildren instead of ViewChildren

ContentChildren(ItemDirective) buttons: QueryList<ItemDirective>;
  • Related