Angular Material 7 下拉菜单
<mat-select>用于创建<select>标签,以增强基于Angular Material设计的样式。
在本章中,我们将展示使用Angular Material绘制select控件所需的配置。
创建 Angular 应用
按照以下步骤创建应用程序
1.创建一个名为materialApp的项目。
2.修改app.module.ts, app.component.ts, app.component.css and app.component.htmls。保持其余文件不变。
3.编译并运行程序。
下面是修改后的app.module.ts文件内容。
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatSelectModule} from '@angular/material' import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MatSelectModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
下面是修改后的app.component.ts文件内容.
import { Component } from '@angular/core'; import { FormControl } from "@angular/forms"; export interface Food { value: string; display: string; } @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'materialApp'; selectedValue: string; foods: Food[] = [ {value: 'steak', display: 'Steak'}, {value: 'pizza', display: 'Pizza'}, {value: 'tacos', display: 'Tacos'} ]; }
下面是修改后的app.component.html文件内容.
<form> <h4>mat-select</h4> <mat-form-field> <mat-select placeholder = "Favorite food" [(ngModel)] = "selectedValue" name = "food"> <mat-option *ngFor = "let food of foods" [value] = "food.value"> {{food.display}} </mat-option> </mat-select> </mat-form-field> <p> Selected food: {{selectedValue}} </p> </form>
结果
细节
首先,我们使用与ngModel绑定的mat-select创建了一个选择。
然后,我们使用mat-option添加了选项。