【问题标题】:viewChildren with directiveviewChildren 有指令
【发布时间】:2018-10-05 20:27:02
【问题描述】:

我想添加一个指令并使用 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
   }

我想要的是使用“myOwnDirective”获取所有元素,但我找不到方法。

我的错误在哪里?

【问题讨论】:

  • 您是否在app.module 中添加了指令?
  • 哦,谢谢!这是我的问题!太感谢了。如果您想将其添加为答案以将其标记为解决方案

标签: angular angular5 angular-directive viewchild


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 2020-04-10
    • 2018-11-28
    • 2019-11-01
    • 2020-02-05
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2017-01-04
    相关资源
    最近更新 更多