[英]Accessing angular2 directive from component
I have created a directive for a textarea (TextAreaExt) and i want to call a method of that directive from a component it is used in. The selector of the directive is "textarea" (no attribute, affects all textarea elements). 我已经为textarea(TextAreaExt)创建了一个指令,我想从它所使用的组件中调用该指令的方法。该指令的选择器是“textarea”(没有属性,影响所有textarea元素)。 In my component if i do the following: 在我的组件中,如果我执行以下操作:
@ViewChild('TextAreaExt') txt: TextAreaExt;
I can call methods on txt successfully. 我可以成功调用txt上的方法。 But what if i had multiple textareas? 但是,如果我有多个textareas怎么办? I would like to do it like this instead: 我想这样做:
@ViewChild('txt') txt: TextAreaExt;
Unfortunately, the above line does not return a TextAreaExt class, but instead returns an ElementRef. 不幸的是,上面的行不返回TextAreaExt类,而是返回一个ElementRef。
How could i solve this problem so that i could have multiple text areas? 我怎么能解决这个问题,以便我可以有多个文本区域?
This should do what you want: 这应该做你想要的:
@ViewChild('txt', {read: TextAreaExt}) txt: TextAreaExt;
If there are more directives, components or other DI tokens registered for an element, read
allows you to specify, which one you want to get returned. 如果有更多的指令,组件或其他DI标记为元素注册,则read
允许您指定要返回的标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.