Angular Material 7 单选按钮
<mat-radiobutton>用于<input type="radio">增强基于Material的样式.
在本章中,我们将展示使用Angular Material绘制单选按钮控件所需的配置。
创建 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 {MatRadioModule} from '@angular/material' import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MatRadioModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
下面是修改后的app.component.css的内容.
.tp-radio-group { display: inline-flex; flex-direction: column; } .tp-radio-button { margin: 5px; } .tp-selected-value { margin: 15px 0; }
下面是修改后的app.component.ts的内容.
import { Component } from '@angular/core'; import { FormControl } from "@angular/forms"; import { Validators } from "@angular/forms"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'materialApp'; favoriteSeason: string; seasons: string[] = ['Winter', 'Spring', 'Summer', 'Autumn']; }
下面是修改后的file app.component.html内容.
<mat-radio-group class = "tp-radio-group" [(ngModel)] = "favoriteSeason"> <mat-radio-button class = "tp-radio-button" *ngFor = "let season of seasons" [value] = "season"> {{season}} </mat-radio-button> </mat-radio-group> <div class = "tp-selected-value"> Selected Season: {{favoriteSeason}} </div>
结果
细节
首先,我们使用与ngModel绑定的mat-radio-group创建了一个单选按钮组。
然后,我们使用mat-radio-button添加了单选按钮。