指令中的调用函数 [英] Calling function in directive

查看:115
本文介绍了指令中的调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to call a public function which is inside my directive from component by getting hold of the directive via viewchild like this

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

但是我收到myFunction不存在的错误. 有没有办法调用指令之外的函数?

But I get error that the myFunction does not exist. Is there a way to call a function which is iniside a directive?

推荐答案

演示-如何从组件-检查浏览器的 控制台


1),我希望您 导入myDirective指令 .

DEMO - How to call Directive's function from Component - check browser's console


1) I hope you are importing myDirective directive.

import {myDirective} from './Directive';

2)

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

3)

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

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

4) Or some button's click event

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

这篇关于指令中的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆