Currently in the process of learning Angular 10, but encountering a challenge
I have an HTML document that validates a form group in my component. When I set a value for a textbox from my component, the value is displayed correctly, but my submit button claims it is invalid (required).
Allow me to demonstrate....
Component
export class PersonalComponent implements OnInit {
personalForm = new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required,
Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")])
});
public name: string = '';
public email: string = '';
public submitted = false;
Method
getPersonalData() {
this.activatedRoute.params.subscribe(prm => {
this.service.getPersonal(prm['id']).subscribe(data => {
this.name = data.name;
this.email = data.email;
},
err => {
console.log(err);
});
})
}
Save method
onSave(form: Personal) {
this.submitted = true;
if (this.personalSaveForm.valid) {
this.service.postPersonal(form).subscribe(data => {
console.log('saved');
},
err => {
console.log(err);
});
}
}
HTML document
<form [formGroup]="personalSaveForm" (ngSubmit)="onSave($event)">
<div class="col-sm-3">
<label for="name" class="col-form-label">Name</label>
</div>
<div class="col-sm-3">
<input type="text" id="name" value="{{name}}" [ngClass]="{'form-submitted': submitted}" formControlName="name" class="form-control" required />
</div>
<div class="col-sm-3">
<label for="email" class="col-form-label">Email</label>
</div>
<div class="col-sm-3">
<input type="text" id="email" value="{{email}}" [ngClass]="{'form-submitted': submitted}" formControlName="name" class="form-control" required />
</div>
<div class=" col-sm-12 align-items-right">
<button type="submit" id="btnSave" class="btn btn-primary" style="float: right;">Next</button>
</div>
As can be observed, even though the component sets a default value for the textbox, the validation persists when the button is clicked!!! despite having a value!
Thank you