I am just trying to show a cross mark when the username is blank or is not with required pattern and show a tick if input entered is valid.Bootstrap is-active and is-inactive class help it. Below is the code i tried with. I only get username is undefined. I seem to have gone wrong with implementation. Could you please help rectify?
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<input
type="text"
placeholder="Username / Email"
class="form-control"
formControlName="username"
[ngClass]="username.errors?'is-invalid':'is-valid'"
name="username"
id="username"
/>
</form>
In ts
profileForm = new FormGroup({
username: new FormControl('',[Validators.required,Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")])
});
in .ts add
get userName() {
return this.profileForm.get('userName');
}
in html add
[ngClass]="userName.hasError('pattern')" ? "is-invalid": "is-valid"
if you wish not to add any code in .ts file use
[ngClass]="profileForm.controls['userName'].hasError('pattern')" ? "is-invalid": "is-valid"
There is indeed no username
property in your component. So yes, username
is undefined.
The only property we know about is named profileForm
. You can get its control named username using profileForm.get('username')
, and you can test if this control is valid using profileForm.get('username').valid
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.