【发布时间】:2021-09-30 13:51:09
【问题描述】:
我有一个指令
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appDirOne]',
exportAs: 'appDirOne'
})
export class DirOneDirective {
status: boolean = false;
constructor() { }
}
在我的另一个指令中 - 当我点击我的情况下的托管元素时,我想要访问第一个指令的属性值的按钮。
<button appDirTwo>Btn</button>
第二个指令
import { DirOneDirective } from './dir-one.directive';
@Directive({
selector: '[appDirTwo]',
exportAs: 'appDirTwo'
})
export class DirTwoDirective {
@HostListener('click') onClick() {
// access to the status property value of the directiveOne
}
}
我尝试了什么
我尝试在构造函数中添加它
import { DirOneDirective } from './dir-one.directive';
@Directive({
selector: '[appDirTwo]',
exportAs: 'appDirTwo'
})
export class DirTwoDirective {
constructor(private directiveOne: DirOneDirective) { }
@HostListener('click') onClick() {
}
}
但我明白了
core.js:4197 ERROR NullInjectorError: R3InjectorError(AppModule)[DirOneDirective -> DirOneDirective -> DirOneDirective]: NullInjectorError: No provider for DirOneDirective!
错误。
我想提一下,这两个指令都在我的 app.module.ts 文件中。
例如,如果我尝试在 HTML 中使用我的directiveOne
<button appDirOne>Btn</button>
然后我没有此提供程序错误消息。 仅当我尝试在其他指令中作为服务注入时才会发生这种情况。
【问题讨论】:
-
基本上,如果你想在指令之间共享数据,你需要一个服务。