Search code examples
angulartypescriptangular-material2angular-ng-if

mat-option selected base on if condition


I want to make a mat-option pre checked base on an if condition.

<div class='form'>
  <mat-form-field color='accent'>
  <!-- if UserAccount is not null, 'Yes' should be pre selected -->
    <mat-select class='form-control' placeholder='user account exists' [(ngModel)]='UserAccountExists' name='UserAccountExists' required value=! data.UserAccount.trim() ? "Yes" : "No">
      <mat-option [value]='"Yes"'>Yes </mat-option>
      <mat-option [value]='"No"'>No </mat-option>
    </mat-select>
    <mat-error *ngIf='formControl.invalid'>{{getErrorMessage()}}</mat-error>
  </mat-form-field>
</div>

<!-- if "Yes" is selected, this field is 'required' -->
<div class='form'>
  <mat-form-field color='accent'>
    <input matInput #inputstate class='form-control' placeholder='Username' [(ngModel)]='data.username' name='Username' required>
    <mat-error *ngIf='formControl.invalid'>{{getErrorMessage()}}</mat-error>
  </mat-form-field>
</div>

  1. The first <div> : If the UserAccount exists, "Yes" should be prechecked.

  2. If "Yes" is selected, in the second <div>, <input> is required

Can someone please help?

Thank you


Solution

  • <mat-select class='form-control' placeholder='user account exists' [(ngModel)]='UserAccountExists' name='UserAccountExists' required>
      <mat-option value="Yes">Yes </mat-option>
      <mat-option value="No">No </mat-option>
    </mat-select>
    
    ...
    
    <input matInput class='form-control' placeholder='Username' [(ngModel)]='data.username' name='Username' [required]="UserAccountExists === 'Yes'">
    

    In your Component, once you fetched your data :

    this.UserAccountExists = !!data.UserAccount ? 'Yes' : 'No';