在Angular 7中,在函数中调用指令可以通过以下步骤完成:
MyDirective
:import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective {
constructor(private elementRef: ElementRef) { }
public doSomething(): void {
// 在这里执行指令的操作
console.log('指令被调用');
}
}
MyDirective
:import { Component, ViewChild } from '@angular/core';
import { MyDirective } from './my.directive';
@Component({
selector: 'app-my-component',
template: `
`
})
export class MyComponent {
@ViewChild('myDirectiveRef', { static: false, read: MyDirective })
private myDirective: MyDirective;
public callDirective(): void {
this.myDirective.doSomething();
}
}
在上面的示例中,我们在模板中使用myDirective
指令并给它一个引用#myDirectiveRef
。然后,我们使用@ViewChild
装饰器和read
选项来获取对指令实例的引用。最后,在callDirective
函数中,我们可以使用该引用调用指令的方法doSomething()
。
请注意,通过@ViewChild
获取指令实例的过程是异步的,并且默认情况下在组件的ngAfterViewInit
生命周期钩子之后才可用。如果需要在组件的ngOnInit
钩子中使用指令实例,请将static
选项设置为true
。
希望以上代码示例能够帮助你在Angular 7中在函数中调用指令。