Angular Material 7 - 單選按鈕



<mat-radiobutton> 是一個 Angular 指令,用於增強基於 Material Design 風格的 <input type="radio">。

本章將展示使用 Angular Material 繪製單選按鈕控制元件所需的配置。

建立 Angular 應用

請按照以下步驟更新我們在Angular 6 - 專案設定章節中建立的 Angular 應用:

步驟 描述
1 建立一個名為materialApp的專案,如Angular 6 - 專案設定章節中所述。
2 修改app.module.tsapp.component.tsapp.component.cssapp.component.html,如下所述。其餘檔案保持不變。
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 { }

以下是修改後的 CSS 檔案app.component.css的內容。

.tp-radio-group {
   display: inline-flex;
   flex-direction: column;
}
.tp-radio-button {
   margin: 5px;
}
.tp-selected-value {
   margin: 15px 0;
}

以下是修改後的 ts 檔案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'];
}

以下是修改後的 HTML 主檔案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>

結果

驗證結果。

Radio button

詳情

  • 首先,我們使用與 ngModel 繫結的 mat-radio-group 建立了一個單選按鈕組。

  • 然後,我們使用 mat-radio-button 添加了單選按鈕。

廣告