如何从另一个指令更改特定指令引用的属性值



我创建了一个指令,单击按钮后,我会更改它的属性值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;
}
}

所以我有两个不同的参考CCD_ 2和CCD_。

现在我有了另一个指令,当它的元素被点击时,我需要更改第一个指令的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
}
}

在angular中,如果两个指令都在same element上,则可以获得另一个指令的引用。

但是,在您的情况下,这两个指令都在不同的元素中,并且cannot直接引用另一个指令的实例。

为了满足要求,您可以使用services来更新状态。在这种方法中,您需要修改组件html,使其具有另一个属性type来区分这两个指令实例。

以下是相同的示例片段。

https://stackblitz.com/edit/angular-ivy-qbejij?file=src%2Fapp%2Fapp.component.html

最新更新