Calling function in directive

前端 未结 2 1452
走了就别回头了
走了就别回头了 2020-12-29 08:13

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(\'myDi         


        
相关标签:
2条回答
  • 2020-12-29 08:21

    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) Or some button's click event

    click(){
       this.vc.myFunction();
    }
    
    0 讨论(0)
  • 2020-12-29 08:31

    Use @ContentChild(). A directive doesn't have a view.

    Call this.myDirective.nativeElement.myFunction() in ngAfterContentChecked() to ensure that this.myDirective... is already initialized.

    0 讨论(0)
提交回复
热议问题