When subscribing to the ValueChanges
of a form control, you may encounter the error Maximum call stack size exceeded
. It is advisable to manage input changes using events like keyup instead.
Remember to utilize updateValueAndValidity
after adding new Validators to ensure they are applied correctly.
Here is an updated code snippet for your component that should work smoothly now :)
// 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 less than 4 characters")
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 {}
I hope this solution proves helpful to you :)