@viewchild for directive always return element ref instead of directive reference- angular5

@viewchild for directive always return element ref instead of directive reference- angular5

我目前正在做一个项目,我需要根据组件传递一些@input 值。因此,该指令将相应地起作用。但问题是我无法获得该指令的参考。相反,我只得到了 return 中的 elementRef。请参考下面的 stackblitz 示例以获取更多参考。

https://stackblitz.com/edit/angular-feptw3

有多种修复方法:

1) 使用 read 选项:

@ViewChild("myCustomDir", { read: MyCustomDirective}) myCustomDir: MyCustomDirective;

Example

另请参阅:

2) 使用 exportAs

directive.ts

@Directive({
  selector: "[myCustom]",
  exportAs: 'myCustom'
  ^^^^^^^^^^^^^^^^^^^^
})
export class MyCustomDirective {
  ...
}

html

<h1 myCustom #myCustomDir="myCustom">
                           ^^^^^^^^

Example

另请参阅: