Angular 用指令查看子对象

Angular 用指令查看子对象,angular,angular5,angular-directive,viewchild,Angular,Angular5,Angular Directive,Viewchild,我想添加一个指令并使用viewChildren来识别它们: // directive.ts @Directive({ selector: '[myOwnDirective]' }) export class MyOwnDirective { constructor() { console.log("hi") //never printed } } //component html: <div myOwnDirective>content 1<

我想添加一个指令并使用viewChildren来识别它们:

// 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
   }
//directive.ts
@指示({
选择器:“[myOwnDirective]”
})
导出类指令{
构造函数(){
console.log(“hi”)//从未打印
}
}
//组件html:
内容1
内容2
内容3
内容4
//组件1.ts:
导出类MyOwnComponent实现AfterViewInit{
@ViewChildren(MyOwnDirective)子对象:QueryList;
构造函数(){
}
ngAfterViewInit(){
}
printElements(){
console.log(this.children)//空
}
我想要的是用“myown指令”获取所有元素,但我找不到如何获取


我的错误在哪里?

您需要在
app.module
中注册指令才能在应用程序中使用。

您需要在
app.module
中注册指令才能在应用程序中使用。

您是否在
app.module
中添加了指令?哦,谢谢!这是我的问题!非常感谢。如果您想将其添加为答案,以便将其标记为解决方案您是否在
应用程序模块中添加了指令?
?哦,谢谢!这是我的问题!非常感谢。如果您想将其添加为答案,以便将其标记为解决方案