在Angular5
为两种类型的表单指定更新模式是可能的:template-driven forms
和reactive forms
.
第一个为你工作。这是反应形式的工作示例
组件.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'form01',
templateUrl: './student.component.html',
styleUrls: ['./student.component.scss']
})
export class StudentComponent implements OnInit {
formTitle:string="Student registration ";
nameForm: FormGroup;
constructor() {
}
ngOnInit() {
this.nameForm = new FormGroup ({
firstname: new FormControl('', {
validators: Validators.required,
asyncValidators: [yourAsyncValidatorFunction],
updateOn: 'blur'
}),
lastname: new FormControl('', {
validators: Validators.required,
asyncValidators: [yourAsyncValidatorFunction],
updateOn: 'blur'
})
});
}
}
HTML
<form [formGroup]="nameForm" novalidate>
<div class="form-group">
<label>What's your first name? </label>
<input class="form-control" formControlName="firstname">
</div>
<div class="form-group">
<label>What's your last name?</label>
<input class="form-control" formControlName="lastname">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
<h3>Hello {{nameForm.value.firstname}} {{nameForm.value.lastname}}</h3>