I'm new to angular and using angular FormControl and facing some issue as below.
I just have a input text with required validator. Based on input entered by user and if the text is valid, I want to enable one button. if input text is invalid, I want to disable button.
When running this, disabled button is never getting enabled. Please check and let me know some suggestions.
Here is my code. I'm using angular reactive forms.
sample.html:
<label for="name">Name: </label>
<input type="text" [formControl]="userName" required>
<p>Value: {{ userName.value }}</p>
<button disabled="(userName.value === '')">{{ userName.value }}</button>
Sample.component.ts
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { NgModule } from '@angular/core';
@Component({
})
export class SampleComponent {
userName = new FormControl('')
ngOnInit(): void {
console.log("entered")
console.log(this.userName.getRawValue());
}
}
First, use property binding to dynamically evaluate the expression. By using HTML property, you're passing a string (userName.value === '')
, which is always a truthy value (so, disabled property is always set to true).
Change this disabled
to [disabled]
Then, you can take advantage of the valid or invalid status of the fromControl, which return a boolean, also lets you perform a better or more complex validation.
Change this [disabled]="(userName.value === '')"
to this [disabled]="userName.invalid"
or [disabled]="!userName.valid"
<label for="name">Name: </label>
<input type="text" [formControl]="userName" required>
<p>Value: {{ userName.value }}</p>
<button [disabled]="userName.invalid">Click me</button>
Don't use inline required attribute, but set the validators during the input set up.
So, remove the required
from your HTML and set the input like this:
import { FormControl, Validators } from '@angular/forms';
...
userName = new FormControl('', [Validators.required]);