[英]How to use property binding in custom directive?
Directive :指令:
// highlight.directive.ts
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
@Input() yourColor: any = 'red';
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = this.yourColor;
}
}
Consumer :消费者:
// app.component.html
<div appHighlight [yourColor]="'blue'">Testing</div>
Result :结果:
Why can't I pass blue
to yourColor
?为什么我不能将
blue
传递给yourColor
?
You should move your code from constructor
to ngOnInit
.您应该将代码从
constructor
移动到ngOnInit
。 Use constructor
in Angular only for injecting dependencies, but ngOnInit
for executing a code when component is mounted. Angular 中的
constructor
仅用于注入依赖项,但ngOnInit
用于在安装组件时执行代码。
Here is more info about that: Difference between Constructor and ngOnInit以下是更多信息: Constructor 和 ngOnInit 之间的差异
Here is a solution using two-way binding:这是使用双向绑定的解决方案:
// highlight.directive.ts
export class HighlightDirective {
yourColor: any = 'red';
ngOnInit() {
// change color in method
this.yourColor = ‘blue’;
}
}
// app.component.html
<div appHighlight style=“background-color= {{yourColor}}”>Testing</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.