我正在尝试从指令中调用方法。 可以说我有指令 我的指令.ts
@Directive({
selector: '[something]',
})
export class myDirective implements OnInit {
....
public myMethod(){
console.log(it works)
}
....
}
和 component.ts(这是我发现的,但在 this.directive 上我得到错误对象可能为空)
@Component({
selector: '...',
templateUrl: '....html',
styleUrls: ['....css'],
})
export class MyComponent implements OnInit {
@ViewChild(myDirective) directive = null
ngOnInit() {
}
onClickFunction() {
return (
this.directive.myMethod();
);
}
}
如何在组件中调用这个方法?
最佳答案
就这样跑
@Component({
selector: '...',
templateUrl: '....html',
styleUrls: ['....css'],
})
export class MyComponent implements OnInit {
@ViewChild(myDirective) directive;
ngOnInit() {
}
onClickFunction() {
return (
this.directive?.myMethod()
);
}
}
在tsconfig.json中添加
"strictPropertyInitialization":false,
关于Angular:从组件中的指令调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68496881/