通过订阅
ValueChanges
表单控件的错误将导致此错误
Maximum call stack size exceeded
,最好使用其事件(例如keyup)控制输入中的更改。
不要忘记使用
updateValueAndValidity
在设置新的验证器以应用它们之后。
这是您的组件的新代码,现在运行良好:)
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
@Component({
selector: 'my-app',
template: `
<div>
<form [formGroup]="userForm">
<section>
<div>
<label>username</label>
<input (keyup)="inputValueChanged($event)" formControlName="username" type="text">
</div>
<button [disabled]="disableSaveButton()">Save</button>
</section>
</form>
</div>
`,
})
export class App implements OnInit {
userForm: formGroup
constructor(private formBuilder: FormBuilder) {
}
disableSaveButton(): boolean {
console.log("is valid:", this.userForm.controls["username"].valid);
return this.userForm.controls["username"].invalid
}
ngOnInit(): void {
this.userForm = this.formBuilder.group({
username: '',
});
}
inputValueChanged(event){
let value = this.userForm.controls["username"].value;
if (value.length > 0) {
console.log("should be invalid if < 4")
this.userForm.controls["username"].setValidators([Validators.required, Validators.minLength(4)]);
} else {
console.log("should be valid")
this.userForm.controls["username"].setValidators([]);
}
this.userForm.controls["username"].updateValueAndValidity();
}
}
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}