gpt4 book ai didi

Angular:从组件中的指令调用方法

转载 作者:行者123 更新时间:2023-12-04 14:54:02 24 4
gpt4 key购买 nike

我正在尝试从指令中调用方法。可以说我有指令我的指令.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com