0

I am using the dropdown to multiple select roles. When click an edit button, I want to 2 roles to be checked out of 3 roles. because the user has two roles admin, dashboards out of admin, dashboards, user.

I will check the roles from the server and the list of roles and if the role names are the same I will make the selected = true. So, I can only select options that selected is true. How do I realize that? This code is based on Angular 8.

typescript

this.user.roles = roles;

role Model

    id: number;
    name: string; 
    selected :boolean;

html

<div class="col-lg-6 kt-margin-bottom-20-mobile">
    <mat-form-field class="mat-form-field-fluid">
        <mat-select placeholder="Role"
                    formControlName="roles"
                    multiple>
            <mat-option *ngFor="
                    let role of roles$ | async " [value]="role">
                {{ role.name }}
            </mat-option>
        </mat-select>
        <mat-error *ngIf="isControlHasError('roles','required')">
            <strong>{{ 'AUTH.VALIDATION.REQUIRED_FIELD' | translate }}</strong>
        </mat-error>
    </mat-form-field>
</div>

dumb11
  • 129
  • 1
  • 9

1 Answers1

1

To make the two way binding on the preselected/default value use [formControl]

<mat-select placeholder="Role" [formControl]="selectedRole" multiple>
  <mat-option *ngFor="let role of roles$ | async " [value]="role.id">
    {{ role.name }}
  </mat-option>
</mat-select>

In the .component.ts your code should look something like this

selectedRole= new FormControl();
ngOnInit(){
  getUserRole()
}

getUserRole(){
...
this.selectedRole.setValue(role.id)  // role = {id:3,name:'user'}
}
mkamranhamid
  • 583
  • 4
  • 18
  • This will give me two options. What I want to do is choosing 2 options out of three. – dumb11 Apr 30 '20 at 05:32
  • `selectedRole` should have the `[value]` field of `` – mkamranhamid Apr 30 '20 at 05:42
  • please check the updated answer also you need to do is to make the `[value]` field not an **object** – mkamranhamid Apr 30 '20 at 05:46
  • other form controls made using what exactly? also using the example I've shared you're not using any `formControlName` property – mkamranhamid Apr 30 '20 at 06:14
  • https://stackoverflow.com/questions/40171914/what-is-the-difference-between-formcontrolname-and-formcontrol I want to keep using formControlName instead of formControl. Can I select two roles? instead of one? – dumb11 Apr 30 '20 at 06:15
  • yes, you can just make sure to populate the role property like [this](https://stackoverflow.com/a/40172083/4822545) – mkamranhamid Apr 30 '20 at 06:19