Search code examples
angularangular5angular-directiveviewchild

viewChildren with directive


I want to add a directive and use viewChildren for identify them:

// directive.ts
@Directive({
  selector: '[myOwnDirective]'
})
export class MyOwnDirective {

   constructor() { 
      console.log("hi") //never printed
    }
}

//component html:

<div myOwnDirective>content 1</div>
<div>content 2</div>
<div>content 3</div>
<div myOwnDirective>content 4</div>
<button (click)="printElements()"></button>

//component.ts:
 export class MyOwnComponent implements AfterViewInit{


  @ViewChildren(MyOwnDirective) children: QueryList<MyOwnDirective>;

   constructor() {

   }

   ngAfterViewInit() {
   }

   printElements(){
     console.log(this.children) // Empty
   }

What I want is get all elements with "myOwnDirective" but I can't find how.

where is my mistake?


Solution

  • You need to register your directive in app.module in order to use in your application.