簡體   English   中英

Angular,我什么時候可以在 angular 指令中使用模板引用變量?

[英]Angular, when can I use template references variables within angular directives?

我是 angular 的新手,我有這個疑問。 使用下一個代碼我有一個非常奇怪的行為:

 <select #selectColor class="btn btn-primary" name="button"> <option [value]="color" *ngFor="let color of COLORS">{{color}}</option> </select> <p customDirective [ngStyle]="{'color':selectColor.value}"> Test paragraph </p>

此代碼在瀏覽器控制台中顯示下一個錯誤,但它不起作用:

ExpressionChangedAfterItHasBeenCheckedError:表達式在檢查后已更改。 以前的值:'顏色:'。 當前值:'顏色:黃色'。

但是當我將鼠標移到元素上時它會“起作用”並改變顏色,因為 customDirective 已經定義了下一個方法:

@HostListener('mouseenter') mouseEnter(){
    //Some code
}

@HostListener('mouseleave') mouseLeave(){
    //Some code
}

我在以下位置上傳了一個演示: https://angular-zxhhml.stackblitz.io

謝謝。

您正在嘗試將模板變量的值綁定到指令。 您不想使用屬性綁定。

您可以通過添加帶有任意表達式的(change)事件處理程序來強制更新綁定的模板變量。

組件.html

<select class="btn btn-primary" name="button" #selectColor (change)="0">
  <option [value]="color" *ngFor="let color of COLORS">{{color}}</option>
</select>

<p customDirective [ngStyle]="{'color':selectedColor}">
  Test paragraph
</p>

當然,更標准(在我看來)和更簡單的方法是使用屬性綁定。

[(ngModel)]="selectedColor" ,然后綁定到selectedColor 組件中沒有嚴格要求任何屬性,但為了清楚起見,我總是建議添加一個。

演示: https://stackblitz.com/edit/angular-lz1cae

在創建組件/指令時,Angular 執行一組稱為生命周期掛鈎的方法。 此處描述了此機制:

https://angular.io/guide/lifecycle-hooks

問題是這個生命周期的所有方法都在同一個 javascript 虛擬機輪次上執行,當您的 select 創建時,將選擇第一個值(此處為黃色),並導致該錯誤。

如上一個答案所述,一種解決方案是使用 ngModel 來跟蹤所選顏色。 為了 select 默認第一個顏色,我使用 setTimeout function 允許在下一個 javascript vm 輪次上推遲執行並避免先前的錯誤。

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';
  COLORS = ['yellow', 'red', 'blue'];
  selectedColor: string;

  ngAfterViewInit(): void {
    setTimeout(() => {
      this.selectedColor = this.COLORS[0];
    });    
  }
}

然后使用輸入將所選顏色鏈接到您的指令。

@Directive({
  selector: '[customDirective]'
})
export class CustomDirectiveDirective {

  @Input() color: string;

  constructor(private readonly element: ElementRef) { }

  @HostListener('mouseenter') mouseEnter(){
    // Some code
  }

  @HostListener('mouseleave') mouseLeave(){
    // Some code
  }

}

這是關於 stackblitz 的示例: https://stackblitz.com/edit/angular-ssq5af

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM