在Angular中,可以使用ngModel
指令来从表单中获取值。下面是一个使用Angular Material的表单组件的示例:
npm install --save @angular/material @angular/cdk @angular/animations
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
MatButtonModule,
MatInputModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Name: {{ name }}
Email: {{ email }}
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name: string;
email: string;
submitForm() {
console.log('Name:', this.name);
console.log('Email:', this.email);
}
}
现在,当用户在表单中输入值并点击提交按钮时,submitForm()
方法会将输入的值打印到控制台。同时,表单下方也会显示输入的值。
这就是使用Angular Material从表单中获取值的基本方法。你可以根据需要扩展和定制表单组件。