0

如何在組件渲染後從指令調用函數?如何在組件渲染後從指令中調用函數?

我有分量:

export class Component { 
    ngAfterContentInit() { 
    // How can i call functionFromDirective()? 
    } 
} 

而且我想調用這個函數:

export class Directive { 

functionFromDirective() { 
//something hapenns 
} 

我怎樣才能做到這一點?

回答

4

您可以從組件模板與ViewChild這樣的檢索指令:

@Directive({ 
    ..., 
    selector: '[directive]', 
}) 
export class DirectiveClass { 
    method() {} 
} 

在您的組件:

import { Component, ViewChild } from '@angular/core' 
import { DirectiveClass } from './path-to-directive' 

@Component({ 
    ..., 
    template: '<node directive></node>' 
}) 
export class ComponentClass { 
    @ViewChild(DirectiveClass) directive = null 

    ngAfterContentInit() { 
    // How can i call functionFromDirective()? 
    this.directive.method() 
    } 
} 
+0

非常感謝!你真的幫助我。 –

0

從一個組件內調用的方法是不是一個好主意。使用指令有助於模塊化設計,但是當您調用該方法時,會從組件中獲取對指令的依賴關係。

相反,該指令應實現AfterViewInit接口:

@Directive({ 
    ..., 
    selector: '[directive]', 
}) 
export class DirectiveClass implements AfterViewInit { 
    ngAfterViewInit(): void {} 
} 

這樣一來,你的組件不必知道該指令什麼。

相關問題