指令:
// 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;
}
}
消費者:
// app.component.html
<div appHighlight [yourColor]="'blue'">Testing</div>
結果:

題
為什么我不能傳遞blue到yourColor?
uj5u.com熱心網友回復:
您應該將代碼從constructor到ngOnInit。使用constructor僅用于注入的依賴關系,但在角ngOnInit用于執行代碼部件被安裝時。
以下是更多資訊:Constructor 和 ngOnInit 之間的差異
uj5u.com熱心網友回復:
這是使用雙向系結的解決方案:
// 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342731.html
標籤:有角的
上一篇:如何以角度動態洗掉MAT_DATE_RANGE_SELECTION_STRATEGY
下一篇:存盤訂閱結果并修補它
