Angular Material 7 - 表單欄位



<mat-form-field> 是一個 Angular 指令,用於建立 Angular 元件的包裝器,並用於應用下劃線、粗體、提示等文字樣式。

以下 Angular 元件可以用於 <mat-form-field> 之內。

  • <input matNativeControl>

  • <textarea matNativeControl>

  • <select matNativeControl>

  • <mat-select>

  • <mat-chip-list>

在本章中,我們將展示在 Angular Material 中使用 mat-form-field 控制元件所需的配置。

建立 Angular 應用

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

步驟 描述
1 按照Angular 6 - 專案設定章節中的說明,建立一個名為materialApp的專案。
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 {MatInputModule,MatOptionModule, MatSelectModule, MatIconModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatInputModule,MatOptionModule, MatSelectModule, MatIconModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }

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

.tp-container {
   display: flex;
   flex-direction: column;
}
.tp-container > * {
   width: 100%;
}

以下是修改後的 HTML 主機檔案app.component.html的內容。

<div class = "tp-container">
   <mat-form-field appearance = "standard">
      <input matInput placeholder = "Input">
      <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
      <mat-hint>Sample Hint</mat-hint>
   </mat-form-field>
   <mat-form-field appearance = "fill">
      <textarea matInput placeholder = "Textarea"></textarea>
   </mat-form-field>
   <mat-form-field appearance = "outline">
      <mat-select placeholder = "Select">
         <mat-option value = "A">A</mat-option>
         <mat-option value = "B">B</mat-option>
         <mat-option value = "C">C</mat-option>      
      </mat-select>
   </mat-form-field>
</div>

結果

驗證結果。

Form Field

詳情

  • 首先,我們使用 mat-form-field 包裝器建立了一個表單欄位。我們使用 appearance 屬性更改了表單欄位的外觀。

  • 然後,將表單控制元件新增到表單欄位。

廣告
© . All rights reserved.