我正在测试一个简单的应用程序。这些是我的文件:
home.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: 'home.component.html'
})
export class HomeComponent {
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = new FormGroup({
'firstName': new FormControl('', Validators.required),
'password': new FormControl('', Validators.minLength(5))
});
}
onSubmit() {
console.log('model-based form submitted');
console.log(this.form);
}
}
这是模板文件:
<section class="sample-app-content">
<h1>Model-based Form Example:</h1>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-field">
<label>First Name:</label>
<input type="text" formControlName="firstName">
</div>
<div class="form-field">
<label>Password:</label>
<input type="text" formControlName="password">
</div>
<p>
<button type="submit" [disabled]="!form.valid">Submit</button>
</p>
</form>
但它不认识Validators
井,因为当我写它时,firstname
它启用了提交按钮,然后如果我把名字放在空白处,输入永远不会变成红色。
我究竟做错了什么?
编辑:
我在这里创建了一个演示