我是 Angular 的新手,并且繼承了要在其上構建的代碼。有一個這樣的輸入表單:
<mat-form-field appearance="fill" color="accent">
<mat-label>Customer Name</mat-label>
<input matInput [readonly]="currentUser.userRole > 2" required maxlength="30" type="text"
[formControl]="customerName" value={{customerName.value}}>
<mat-error *ngIf="customerName.invalid">{{getRequiredErrorMessage()}<mat-error>
</mat-form-field>
有人可以解釋這一切意味著什么嗎?代碼失敗
“無法讀取 null 的屬性(讀取 'userRole')”
uj5u.com熱心網友回復:
readonly如果userRoleforcurrentUser必須大于 2 ,則在屬性的輸入中包含此條件。
該物件currentUser可能具有undefined該特定屬性的值。試試這個,看看它是否修復了錯誤
<input
matInput
[readonly]="currentUser?.userRole > 2" //Optional chaining operator "?"
required
maxlength="30"
type="text"
[formControl]="customerName"
value={{customerName.value}}
>
或者,如果您想為啟用該readonly屬性做更多的事情,您可以像這樣附加一個函式:
<input
matInput
[readonly]="validateReadOnly(currentUser)"
required
maxlength="30"
type="text"
[formControl]="customerName"
value={{customerName.value}}
>
validateReadOnly(currentUser: YourDataTypeHere): boolean {
// ... do some other logic needed here
return currentUser?.userRole > 2;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/386098.html
標籤:有角的
上一篇:如何將從webapi回傳的自定義物件陣列的HttpResponse回應分配給typescriptangular中相同陣列型別的物件?
