在 mat-select 中设置默认选项

我有一个简单的选择形式的选项字段在我的角材料项目:

组件

<mat-form-field>
<mat-select [(value)]="modeSelect" placeholder="Mode">
<mat-option value="domain">Domain</mat-option>
<mat-option value="exact">Exact</mat-option>
</mat-select>
</mat-form-field>

其中 [(value)]="modeSelect"绑定到 Component ent.ts 文件中的 modeSelect 属性

我想使它这样的 <mat-option value="domain">Domain</mat-option>是默认选择的页面加载。

ng-selected对我不起作用

298425 次浏览

Working StackBlitz

No need to use ngModel or Forms

In your html:

<mat-form-field>
<mat-select [(value)]="selected" placeholder="Mode">
<mat-option value="domain">Domain</mat-option>
<mat-option value="exact">Exact</mat-option>
</mat-select>
</mat-form-field>

and in your component just set your public property selected to the default:

selected = 'domain';

Try this:

<mat-select [(ngModel)]="defaultValue">
export class AppComponent {
defaultValue = 'domain';
}

Try this

<mat-form-field>
<mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
<mat-option value="domain">Domain</mat-option>
<mat-option value="exact">Exact</mat-option>
</mat-select>
</mat-form-field>

Component:

export class SelectValueBindingExample {
public modeselect = 'Domain';
}

Live demo

Also, don't forget to import FormsModule in your app.module

I was able to set the default value or whatever value using the following:

Template:

<mat-form-field>
<mat-label>Holiday Destination</mat-label>
<mat-select [(ngModel)]="selectedCity" formControlName="cityHoliday">
<mat-option [value]="nyc">New York</mat-option>
<mat-option [value]="london">London</mat-option>
<mat-option [value]="india">Delhi</mat-option>
<mat-option [value]="Oslo">Oslo</mat-option>
</mat-select>
</mat-form-field>

Component:

export class WhateverComponent implements OnInit {


selectedCity: string;


ngOnInit() {
this.selectedCity = 'london';
}
}

HTML

<mat-form-field>
<mat-select [(ngModel)]="modeSelect" placeholder="Mode">
<mat-option *ngFor="let obj of Array"  [value]="obj.value">\{\{obj.value}}</mat-option>
</mat-select>

Now set your default value to

modeSelect

, where you are getting the values in Array variable.

This issue vexed me for some time. I was using reactive forms and I fixed it using this method. PS. Using Angular 9 and Material 9.

In the "ngOnInit" lifecycle hook

  1. Get the object you want to set as the default from your array or object literal
const countryDefault = this.countries.find(c => c.number === '826');

Here I am grabbing the United Kingdom object from my countries array.

  1. Then set the formsbuilder object (the mat-select) with the default value.
this.addressForm.get('country').setValue(countryDefault.name);
  1. Lastly...set the bound value property. In my case I want the name value.
<mat-select formControlName="country">
<mat-option *ngFor="let country of countries" [value]="country.name" >
\{\{country.name}}
</mat-option>
</mat-select>

Works like a charm. I hope it helps

Normally you are going to do this in your template with FormGroup, Reactive Forms, etc...

this.myForm = this.fb.group({
title: ['', Validators.required],
description: ['', Validators.required],
isPublished: ['false',Validators.required]
});

I would like to add to Narm's answer here and have added the same as a comment under her answer.

Basically the datatype of the value assigned to [(value)] should match the datatype of the [value] attribute used for the mat-options. Especially if some one populates the options using an *ngFor as below

<mat-form-field fxHide.gt-sm='true'>
<mat-select [(value)]="heroes[0].id">
<mat-option *ngFor="let hero of heroes" [value]="hero.id">\{\{ hero.name }}</mat-option>
</mat-select>
</mat-form-field>

Notice that, if you change the [(value)]="heroes[0].id" to [(value)]="heroes[0].name" it won't work as the data types don't match.

These are my findings, please feel free to correct me if needed.

It took me several hours to figure out this until the similarity of the datatypes between the array and that of the default value worked for me...

Using Form Model (Reactive Forms)

--- HTML code ---

<form [formGroup]="patientCategory">
<mat-form-field class="full-width">
<mat-select placeholder="Category" formControlName="patientCategory">
<mat-option>--</mat-option>
<mat-option *ngFor="let category of patientCategories" [value]="category">
\{\{category.name}}
</mat-option>
</mat-select>
</mat-form-field>

--- ts code ---

ngOnInit() {
this.patientCategory = this.fb.group({
patientCategory: [null, Validators.required]
});


const toSelect = "Your Default Value";
this.patientCategory.get('patientCategory').setValue(toSelect);
}

Without form Model

--- HTML code ---

<mat-form-field>
<mat-label>Select an option</mat-label>
<mat-select [(value)]="selected">
<mat-option>None</mat-option>
<mat-option value="option1">Option 1</mat-option>
<mat-option value="option2">Option 2</mat-option>
<mat-option value="option3">Option 3</mat-option>
</mat-select>
</mat-form-field>

--- ts code ---

selected = 'option1';

Here take care about type of the value assigning

On your typescript file, just assign this domain on modeSelect on your ngOnInit() method like below:

ngOnInit() {
this.modeSelect = "domain";
}

And on your html, use your select list.

<mat-form-field>
<mat-select  [(value)]="modeSelect" placeholder="Mode">
<mat-option value="domain">Domain</mat-option>
<mat-option value="exact">Exact</mat-option>
</mat-select>
</mat-form-field>

Read this if you are populating your mat-select asyncronously via an http request.

If you are using a service to make an api call to return the mat-select options values, you must set the 'selected value' on your form control as part of the 'complete' section of your service api call subscribe().

For example:

this.customerService.getCustomers().subscribe(
customers => this.customers = customers ,
error => this.errorMessage = error as any,
() => this.customerSelectControl.setValue(this.mySelectedValue));

HTML :

<mat-select [(ngModel)]="currentCompany" placeholder="All" (selectionChange)="selectionChange($event.value)">
<mat-option>All</mat-option>
<mat-option *ngFor="let company of logsCompanies" [value]="company">
\{\{company}}
</mat-option>
</mat-select>

TS : Filter by company name; If the selected data is 'All', it returns undefined and if it is undefined, I return all the data.

selectionChange(e: any)
{
if (e == undefined) {
this.dataSource.data = this.allDataSource;
}
else {
this.logDataSource.data = this.allDataSource;
this.logDataSource.data = this.logDataSource.data.filter(x => x.companyName == e);
}
}

Here is the solution

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


interface Food {
value: string;
viewValue: string;
}


interface Car {
value: string;
viewValue: string;
}


/**
* @title Basic select with initial value and no form
*/
@Component({
selector: 'select-initial-value-example',
templateUrl: 'select-initial-value-example.html',
})
export class SelectInitialValueExample {
foods: Food[] = [
{ value: 'steak-0', viewValue: 'Steak' },
{ value: 'pizza-1', viewValue: 'Pizza' },
{ value: 'tacos-2', viewValue: 'Tacos' }
];
cars: Car[] = [
{ value: 'ford', viewValue: 'Ford' },
{ value: 'chevrolet', viewValue: 'Chevrolet' },
{ value: 'dodge', viewValue: 'Dodge' }
];
selectedFood = this.foods[2].value;
selectedCar = this.cars[0].value;


selectCar(event: Event) {
this.selectedCar = (event.target as HTMLSelectElement).value;
}
}

In template use it lie this

<h4>Basic mat-select with initial value</h4>
<mat-form-field appearance="fill">
<mat-label>Favorite Food</mat-label>
<mat-select [(value)]="selectedFood">
<mat-option></mat-option>
<mat-option [value]="option.value" *ngFor="let option of foods">\{\{ option.viewValue }}</mat-option>
</mat-select>
</mat-form-field>
<p>You selected: \{\{selectedFood}}</p>


<h4>Basic native select with initial value</h4>
<mat-form-field appearance="fill">
<mat-label>Favorite Car</mat-label>
<select matNativeControl (change)="selectCar($event)">
<option value=""></option>
<option *ngFor="let option of cars" [value]="option.value" [selected]="selectedCar === option.value">\{\{
option.viewValue }}</option>
</select>
</mat-form-field>
<p>You selected: \{\{selectedCar}}</p>

In order to set default value for mat-select drop down use the below method using reactive form in angular.

HTML

<mat-select[(value)]="selectedId" [formControl]="foodId">
<mat-option *ngFor="let food of foods" [value]="food.value">
\{\{food.name}}
</mat-option>
</mat-select>

TS file

foodId = new FormControl(foods[0].value); // to set the first element as default


FYI - Based on the requirement you can change the value

You can use ngModel to link them like so, it just needs to be linked to the actual value...

<mat-form-field>
<mat-select [(ngModel)]="domain" placeholder="Mode">
<mat-option value="domain">Domain</mat-option>
<mat-option value="exact">Exact</mat-option>
</mat-select>
</mat-form-field>

I will post another answer to this post for people who don't have a simple string, but an object which they want their users to select. Simply bind the object to mat-selects [(value)] and also pass a [compareWith] function like so:

<mat-form-field>
<mat-select [(value)]="selectedCountry" [compareWith]="isSameCountry">
<mat-option *ngFor="let country of countries"
[value]="country">\{\{ country.name }}</mat-option>
</mat-select>
</mat-form-field>
public isSameCountry(countryA?: Country, countryB?: Country): boolean {
return !!countryA && countryA.isoCode === countryB?.isoCode;
}

No need to deal with the form object then.

Reference: Angular Material: mat-select not selecting default