@viewchild for 指令总是返回元素 ref 而不是指令参考 - angular5

Posted

技术标签:

【中文标题】@viewchild for 指令总是返回元素 ref 而不是指令参考 - angular5【英文标题】:@viewchild for directive always return element ref instead of directive reference- angular5 【发布时间】:2018-11-13 17:12:49 【问题描述】:

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

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

【问题讨论】:

【参考方案1】:

有办法解决它:

1) 使用read 选项:

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

Example

另见:

How to get reference of the component associated with ElementRef in Angular 2

2) 使用exportAs

directive.ts

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

html

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

Example

另见:

What is #auto attribute here and why it is required

【讨论】:

感谢您的快速回复。有用。非常感谢。

以上是关于@viewchild for 指令总是返回元素 ref 而不是指令参考 - angular5的主要内容,如果未能解决你的问题,请参考以下文章