Angular自定义指令如何使用属性绑定?为何yourColor无法接收blue值?
问题根因
你遇到的传值失效问题是因为你在指令的构造函数中读取@Input属性值,这不符合Angular的生命周期执行逻辑:
Angular中@Input装饰的入参绑定操作是在构造函数执行完成后才会触发的,构造函数运行阶段yourColor只会取你声明时定义的默认值red,父组件传入的blue此时还没有被赋值到指令实例上。
解决方案
提供两种常用的修复方案,原有调用侧代码无需修改:
方案1:使用ngOnInit生命周期钩子读取入参
ngOnInit会在所有@Input入参绑定完成后触发,此时可以正确拿到传入的自定义值:
// highlight.directive.ts import { Directive, ElementRef, Input, OnInit } from '@angular/core'; @Directive({ selector: '[appHighlight]', }) export class HighlightDirective implements OnInit { @Input() yourColor: any = 'red'; constructor(private el: ElementRef) {} ngOnInit() { this.el.nativeElement.style.backgroundColor = this.yourColor; } }
方案2:使用@Input setter监听值变化
如果需要支持入参动态修改后自动更新样式,可以用setter的方式实现:
// highlight.directive.ts import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[appHighlight]', }) export class HighlightDirective { private _yourColor: any = 'red'; @Input() set yourColor(color: any) { this._yourColor = color; this.el.nativeElement.style.backgroundColor = color; } get yourColor() { return this._yourColor; } constructor(private el: ElementRef) {} }
额外排查点:如果修改生命周期后依然无效,请确认你已经将
HighlightDirective添加到了对应功能模块的declarations数组中,否则指令不会生效,属性绑定自然也无法触发。
内容的提问来源于stack exchange,提问作者Display Name
相关产品推荐
相关产品推荐

