Set Default Value in Multi Select Angular Material?

By Hardik Savani October 26, 2021 Category : Angular

Today, angular material multi select dropdown default value is our main topic. you will learn how to set default value in angular material multi select dropdown. This post will give you simple example of how to set default value in multiselect dropdown in angular material. This article will give you simple example of set default value in multi mat-select angular.

You can set default value in material multi select dropdown in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11 and angular 12.

I will give you simple example of how to set default value in multiselect dropdown in angular material. here you can see ts file code and html file code as bellow:

Let's see bellow example code here:

src/app/app.component.ts

import { Component } from '@angular/core';

import { FormBuilder, FormGroup, Validators} from '@angular/forms';

interface Website {

value: string;

viewValue: string;

}

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent{

title = 'app-material3';

selectedOption = ['2','3'];

websites: Website[] = [

{value: '1', viewValue: 'ItSolutionStuff.com'},

{value: '2', viewValue: 'HDTuto.com'},

{value: '3', viewValue: 'Nicesnippets.com'},

{value: '4', viewValue: 'laravel.com'},

{value: '5', viewValue: 'npm.com'},

{value: '6', viewValue: 'google.com'}

];

form: FormGroup = new FormGroup({});

constructor(private fb: FormBuilder) {

this.form = fb.group({

website: [this.selectedOption, [Validators.required]],

})

}

get f(){

return this.form.controls;

}

submit(){

console.log(this.form.value);

}

}

src/app/app.component.html

<h1>Angular Material Multi Select Box with Default Value Example - ItSolutionStuff.com</h1>

<form [formGroup]="form" (ngSubmit)="submit()">

<mat-form-field>

<mat-label>Select Website</mat-label>

<mat-select formControlName="website" multiple>

<mat-option *ngFor="let website of websites" [value]="website.value">

{{website.viewValue}}

</mat-option>

</mat-select>

<mat-error *ngIf="form.get('website')?.hasError('required')">

Please select website

</mat-error>

</mat-form-field>

<button mat-raised-button color="accent">Submit</button>

</form>

Output:

I hope it can help you...