组件 => app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MaterialDropDown, PAYMENT_MODES } from './order.model';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
sampleForm: FormGroup;
paymentModes: MaterialDropDown[];
constructor() {}
ngOnInit() {
this.paymentModes = PAYMENT_MODES;
this.sampleForm = new FormGroup({
payment_mode: new FormControl(null, Validators.required),
});
}
get f() {
return this.sampleForm.controls;
}
onPaymentSelection() {
console.log(this.sampleForm.value.payment_mode);
}
onSubmit() {
console.log(this.sampleForm.value);
}
}
模块 => app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatButtonModule } from '@angular/material/button';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
MatFormFieldModule,
MatSelectModule,
MatButtonModule
],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
模型 => order.model.ts
export interface MaterialDropDown {
value: string;
viewValue: string;
}
export const PAYMENT_MODES: MaterialDropDown[] = [
{ value: 'Cash', viewValue: 'Cash' },
{ value: 'cheque', viewValue: 'Cheque' },
{ value: 'dd', viewValue: 'Demand Draft' },
{ value: 'neft', viewValue: 'NEFT' },
{ value: 'rtgs', viewValue: 'RTGS' },
{ value: 'upi', viewValue: 'UPI' }
];
查看 => app.component.html
<form [formGroup]="sampleForm" (ngSubmit)="onSubmit()">
<mat-form-field>
<mat-label>Payment Mode</mat-label>
<mat-select formControlName="payment_mode" (ngModelChange)="onPaymentSelection($event)">
<mat-option *ngFor="let payment_mode of paymentModes" [value]="payment_mode.value">
{{ payment_mode.viewValue }}
</mat-option>
</mat-select>
<mat-hint *ngIf="!f.touched">Please select a valid Payment Mode.</mat-hint>
<div *ngIf="!f.payment_mode.valid && f.payment_mode.touched">
<mat-error *ngIf="f.payment_mode.errors.required">Payment Mode field is required</mat-error>
</div>
</mat-form-field>
<button type="submit" mat-raised-button color="primary" [disabled]="sampleForm.invalid">Save</button>
</form>
<p style="color: #f00">Check Console for outputs</p>
CSS => app.component.css
mat-form-field { width: 280px; margin-right: 35px}
工作演示