【发布时间】:2021-09-29 18:04:43
【问题描述】:
我创建了指令,点击按钮我更改它的属性值status。
{{ tempDirOne.status }}
<button appDirOne #tempDirOne="appDirOne">Diritive One first btn</button>
{{ tempDirTwo.status }}
<button appDirOne #tempDirTwo="appDirOne">Diritive One second btn</button>
指令一
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appDirOne]',
exportAs: 'appDirOne'
})
export class DirOneDirective {
status: boolean = false;
constructor() { }
@HostListener('click') onClick() {
this.status = !this.status;
}
}
所以我有两个不同的参考tempDirOne 和tempDirTwo。
现在我有另一个指令,当单击它的元素时,我需要更改第一个指令的 status 属性。
<button appDirTwo #tempDurSecondDirective="appDirTwo">Directive two button</button>
第二个指令
@Directive({
selector: '[appDirTwo]',
exportAs: 'appDirTwo'
})
export class DirTwoDirective {
constructor() { }
@HostListener('click') onClick() {
// change hier the status property of directive one - but
// because there are two instances - change manually eiter on tempDirOne or tempDirTwo
}
}
【问题讨论】:
-
你能创建 stackblitz 吗?
-
您可以创建一个单独的服务并将其注入到两个指令中。将状态存储到服务中,angular.io/guide/architecture-services。
-
否则您需要一个
@OutputEventEmiter 将状态更改从 Dir2 传播到其父级,并让父级通过@Input参数将该更改传播到 Dir1