要演示Angular 5中的响应式表单,您可以按照以下步骤进行操作:
npm install -g @angular/cli
ng new angular-forms-example
cd angular-forms-example
ng generate component reactive-form
app.component.html
文件中,添加以下代码:
reactive-form.component.ts
文件中,添加以下代码:import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required]
});
}
onSubmit() {
if (this.myForm.valid) {
console.log(this.myForm.value);
}
}
}
reactive-form.component.html
文件中,添加以下代码:
ng serve --open
现在,您将在浏览器中看到一个具有响应式表单的页面。您可以尝试输入不同的数据并提交表单,验证将根据您所定义的验证规则进行处理。当表单有效时,将在控制台上打印出表单值。
希望这可以帮助到您!