【问题标题】:Calling function in directive在指令中调用函数
【发布时间】:2017-03-19 05:18:06
【问题描述】:

我试图通过像这样通过 viewchild 获取指令来从组件调用我的指令中的公共函数

 @ViewChild('myDirective') myDirective;
 ....
 myDirective.nativeElement.myFunction();

但我收到 myFunction 不存在的错误。 有没有办法调用指令内部的函数?

【问题讨论】:

标签: angular


【解决方案1】:

DEMO - How to call Directive's function from Component - 检查浏览器的 控制台


1)我希望您导入 myDirective 指令
import {myDirective} from './Directive';

2)

@ViewChild(myDirective) vc:myDirective;   ///<<<@@@removed '' from ('myDirective')

3)

ngAfterViewInit(){   
    this.vc.myFunction();                 ///<<@@@ no need to use nativeElement
}

4)或者某个按钮的点击事件

click(){
   this.vc.myFunction();
}

【讨论】:

  • 谢谢,这与 ViewChild 一起使用,并通过设置指令而不是我与“”一起使用的#myDirective。但是,当使用多个指令时,它会让人想知道如何实现这一点。在这种情况下,我只使用一个指令。
  • 使用多个指令意味着如何和什么???。提出问题并获得答案。告诉我们您的情况,我们会尽力解决。
  • 谢谢,我的意思是如果你有例如从你的 plunkr

    Angular2

    Test 3

    你将如何引用 h3 指令
  • 正是我要找的,真棒!
  • 这似乎已被弃用。无法读取未定义的属性“callme”。请看stackblitz.com/edit/angular-playground-1di2vk?file=app/…
【解决方案2】:

使用@ContentChild()。指令没有视图。

ngAfterContentChecked() 中调用this.myDirective.nativeElement.myFunction() 以确保this.myDirective... 已经初始化。

【讨论】:

  • 感谢您的回复。我将 ViewChild 更改为 ContentChild 但现在 myDirective 未定义。知道为什么会发生这种情况吗?
  • 你找到原因了吗?
  • 指令没有视图,它只能有内容——它的宿主元素的内容。
  • 使用 ngAfterContentChecked,使用“if (this.vc) {this.vc.myFunction()}”检查不为空和未定义 - 检查 ng5 和 ng6
  • 这应该是接受的答案。您的解决方案对我帮助很大。非常感谢。
猜你喜欢
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
相关资源
最近更新 更多