Skip to content Skip to sidebar Skip to footer

Angular Mat Select Value Default Value From Api

How do we set the default value to a select menu in the latest angular? I have getAccountRoleDropdown that gets the list of roles and populates it to a select menu, I also have get

Solution 1:

You can achieve this by using ngModel, I have modified your code, (HTML & TYPESCRIPT) please have a look below:

component.ts

generalUserDetails: any;
  accountRoles: Array<any> = [];
  defaultRole: any; // save your default in this variable

  constructor() {
    this.generalUserDetails = {
      "id": 1,
      "invitedByDate": "08/10/2021 02:06 am",
      "identityId": null,
      "title": "COO",
      "isSso": null,
      "ssocredentials": "",
      "userAccountDto": [
        {
          "id": 1,
          "accountId": 4,
          "userRoleDto": {
            "id": 6,
            "roleName": "Transaction Super User"
          }
        }
      ],
      "accountId": 0,
      "roleId": 6,
      "isVerified": null,
      "securityRole": "Transaction Super User",
      "ssoEnabled": "No",
    };
    this.accountRoles = [
      {
        "id": 1,
        "roleName": "Admin"
      },
      {
        "id": 2,
        "roleName": "Broker"
      },
      {
        "id": 5,
        "roleName": "Transaction Manager"
      },
      {
        "id": 6,
        "roleName": "Transaction Super User"
      },
      {
        "id": 7,
        "roleName": "Unlicensed User"
      }
    ];
  }

  ngOnInit() {
    this.getDefaultRole();
  }

  // this method will help you to get default role
  getDefaultRole() {
    if(this.generalUserDetails && this.accountRoles.length) {
      let role = this.accountRoles.find(o=>o.id == this.generalUserDetails.userAccountDto[0].userRoleDto?.id);
      if(role) {
        this.defaultRole = role;
      }
    }
  }

component.html

<mat-form-field>
  <mat-select [(ngModel)]="defaultRole" (selectionChange)="selectChangeHandler($event)">
    <mat-option *ngFor="let role of accountRoles" [value]="role">
      {{role.roleName}}
    </mat-option>
  </mat-select>
</mat-form-field>

<p>You selected: {{defaultRole | json}}</p>

Screenshot with Output enter image description here

Note: Please don't forget to import FormsModule in your app.module

Currently I hardcoded the user Details Data, & account roles but you need to consume already defined method getUserGeneralDetails() & getAccountRoleDropdown() respectively

Solution with ReactiveForm

HTML CODE

<form [formGroup]="securityForm" class="securityForm">

  <label class="label1">Assign Security Role (*)</label>
  <mat-form-field>
    <mat-select [formControl]="roleId" (selectionChange)="selectChangeHandler($event)">
      <mat-option *ngFor="let role of accountRoles" [value]="role.id">
        {{role.roleName}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  
</form>

.TS CODE

import { Component, VERSION } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  AccountRoleIsInProgress: boolean = false;
  accountRoles: Array<any> = [];

  isInProgress: boolean = false;
  data: any;

  securityForm: FormGroup;
  isSso: FormControl;
  ssocredentials: FormControl;
  roleId: FormControl;

  constructor(
    private fb: FormBuilder
  ) {
    this.isSso = new FormControl();
    this.ssocredentials = new FormControl();
    this.roleId = new FormControl();

    this.securityForm = this.fb.group({
      isSso: this.isSso,
      ssocredentials: this.ssocredentials,
      roleId: this.roleId
    });
  }

  ngOnInit(): void {
    this.getUserGeneralDetails();
    this.getAccountRoleDropdown();
    this.getDefaultRole();
  }

  getAccountRoleDropdown() {
    // this.AccountRoleIsInProgress = true;
    // this._accountService
    //   .getAccountRoleDropdown(this.accountId, '')
    //   .pipe(finalize(() => (this.AccountRoleIsInProgress = false)))
    //   .subscribe({
    //     next: res => {
    //       if (res.isSuccess) {
    //         this.accountRoles = res.data;
    //         console.log('this.accountRoles', this.accountRoles);
    //         // this.populateAccountRoleDropdown(res.data);
    //       }
    //     },
    //     error: err => this._notificationService.showError(err),
    //     complete: noop
    //   });
    return [
      {
        "id": 1,
        "roleName": "Admin"
      },
      {
        "id": 2,
        "roleName": "Broker"
      },
      {
        "id": 5,
        "roleName": "Transaction Manager"
      },
      {
        "id": 6,
        "roleName": "Transaction Super User"
      },
      {
        "id": 7,
        "roleName": "Unlicensed User"
      }
    ];
  }

  getUserGeneralDetails() {
    // this.isInProgress = true;
    // this._userProfileService
    //   .getUserGeneralDetails(this.userId, this.accountId)
    //   .pipe(finalize(() => (this.isInProgress = false)))
    //   .subscribe({
    //     next: res => {
    //       if (res.isSuccess) {
    //         this.data = res.data;
    //         console.log('user data', this.data);
    //       }
    //     },
    //     error: err => this._notificationService.showError(err),
    //     complete: noop
    //   });

    return {
      "id": 1,
      "invitedByDate": "08/10/2021 02:06 am",
      "identityId": null,
      "title": "COO",
      "isSso": null,
      "ssocredentials": "",
      "userAccountDto": [
        {
          "id": 1,
          "accountId": 4,
          "userRoleDto": {
            "id": 6,
            "roleName": "Transaction Super User"
          }
        }
      ],
      "accountId": 0,
      "roleId": 6,
      "isVerified": null,
      "securityRole": "Transaction Super User",
      "ssoEnabled": "No",
    };
  }

  // this method will help you to get default role
  getDefaultRole() {
    if(this.data && this.accountRoles.length) {
      let role = this.accountRoles.find(o=>o.id == this.data.userAccountDto[0].userRoleDto?.id);
      if(role) {
        this.roleId.setValue(role.id);
      }
    }
  }

  selectChangeHandler(event) {
    
  }
}

Note: Note: Please don't forget to import ReactiveFormsModule in your app.module.ts


Post a Comment for "Angular Mat Select Value Default Value From Api"