首页 > 解决方案 > 如何从另一个指令更改指令自定义属性的值

问题描述

我正在尝试构建一个指令,该指令将设置/更改位于同一元素上的另一个指令的自定义属性。

所以,#1 是一个第 3 方指令,它有一个名为“已禁用”的自定义 @Input 属性。我想创建一个 #2 指令,以编程方式更改“禁用”的值。这在Angular 8+中可能吗?

我已经尝试过@Input() disabled: boolean;并且可以读取该值,但是当我尝试更改该值时,它什么也没做。我也尝试过使用@HostBinding() disabled: boolean,但该注释只能用于本机属性并导致编译错误。

这是一些使用的代码@Input

import { Directive, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[appMyDirective]',
})
export class AppMyDirective implements OnInit {

  // @HostBinding() disabled: boolean; // results in compile error

  @Input() disabled: any;

  constructor() {}

  ngOnInit() {
    // I can read the value just fine
    console.log(`Value of disabled prop: ${this.disabled}`);

    // But changing the value has no effect on the binding
    this.disabled = true;
  }
}
<div appMyDirective someOtherDirective [disabled]="false"></div>

标签: angular

解决方案


是的,您可以通过简单地注入 的构造函数并调用其属性来访问同一元素上的appMyDirectivefrom 。someOtherDirectiveappMyDirectivesomeOtherDirective

export class SomeOtherDirective implements OnInit {

  constructor(private myDir: MyDirective) {}

  ngOnInit() {
    this.myDir.disabled = true;
  }
}

StackBlitz 示例


推荐阅读