I am new to Angular and inherited code to build on. There is an input form like this:
<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>
Can someone explain what all that means? The code is failing with
"Cannot read properties of null (reading 'userRole')"
CodePudding user response:
You have this in your input for the readonly attribute the condition if userRole for currentUser has to be greater than 2.
The object currentUser maybe has as undefined value for that particular property. Try this and see if it fixes the error
<input
matInput
[readonly]="currentUser?.userRole > 2" //Optional chaining operator "?"
required
maxlength="30"
type="text"
[formControl]="customerName"
value={{customerName.value}}
>
Or, if you want to do something more for enabling the readonly property, you could attach a function to it like this:
<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;
}
