angular - 如何从另一个指令更改指令自定义属性的值
问题描述
我正在尝试构建一个指令,该指令将设置/更改位于同一元素上的另一个指令的自定义属性。
所以,#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>
解决方案
是的,您可以通过简单地注入 的构造函数并调用其属性来访问同一元素上的appMyDirective
from 。someOtherDirective
appMyDirective
someOtherDirective
export class SomeOtherDirective implements OnInit {
constructor(private myDir: MyDirective) {}
ngOnInit() {
this.myDir.disabled = true;
}
}
推荐阅读
- r - 设置 wd 的问题
- python - 用于检查点是在 Cuboid 内部还是外部的 Python 代码
- android - 奇怪的 FloatingActionButton 色调行为
- c++ - Boost Spirit x3 条件(三元)运算符解析器(后续问题)
- r - 如何编写一个使用配对 t 检验比较时间序列数据点的函数
- widget - 用于音量控制栏的 GTK Widget
- php - 在 Laravel 应用程序中散列密码并签入另一个
- javascript - 使用 ResizeObserver 重绘背景会导致在 FireFox 中闪烁
- css - 匹配不在同一级别的 css 选择器
- docker - 带有私有 Google 容器存储库的 Nexus