【问题标题】:How can i change property value of specific directive reference from another directive如何从另一个指令更改特定指令引用的属性值
【发布时间】: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;
  }

}

所以我有两个不同的参考tempDirOnetempDirTwo

现在我有另一个指令,当单击它的元素时,我需要更改第一个指令的 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
  • 否则您需要一个@Output EventEmiter 将状态更改从 Dir2 传播到其父级,并让父级通过 @Input 参数将该更改传播到 Dir1

标签: angular angular-directive


【解决方案1】:

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

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

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

以下是相同的示例 sn-p。

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

【讨论】:

  • 感谢您的回复。但我需要一些东西,我将从指令 2 中选择我将更新哪些参考。在您的示例中,它只是第一个
  • 如果您看到 html sn-p,我确实添加了新的属性类型 =“dir1”。这在指令 1 的 ngOnInit 中进一步引用,以检查要更改的指令值。您可以添加 else 部分来更新实例 2 指令。
  • 您的示例不适用于两个参考。发射值将通过服务对所有引用进行设置。我奉献了
  • 就我在答案中添加的 stackblitz 链接而言,它正在更改指令 1 的状态属性,因为它订阅了与您在问题中提出的内容一致的服务。你有机会玩 stackblitz 吗?您所说的“将通过服务对所有引用设置发射值”是什么意思?
猜你喜欢
  • 2021-09-30
  • 1970-01-01
  • 2015-03-06
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
相关资源
最近更新 更多