Issue
I have already some standard values coming from my web api in my form. The problem is my FromGroup ignores them and sets all the values to null. A value is only not null if i type something by myself into the input. So if im trying to update a user it would reset the whole user.
My Form:
<form [formGroup]="persoForm" (ngSubmit)="onSubmit()">
<div id="firma">
<mat-form-field appearance="standard" id="firm" floatLabel="always">
<mat-label> Firmenbez.:</mat-label>
<input matInput type="text" name="firm" formControlName="firmenBez" [value]="person.firmenbezeichnung"/>
</mat-form-field>
</div>
</form>
TS
persoForm = new FormGroup({
firmenBez: new FormControl(),
})
onSubmit(){ //currently only there to check if the values are still null
console.log(this.persoForm.getRawValue());
}
Solution
The input should take the value from one source, but you're using two sources in your code: one of them is the formControlName and the other one is value.
In Angular Reactive Form, you have to keep the formControlName without value, and handle its value based on your API data:
- If you get the data before initializing the
FormGroup, then you have to initialize it like the following:
// init the form-group when you get the data from the API like the following:
this.personForm = new FormGroup({
firmenBez: new FormControl(this.person.firmenbezeichnung),
});
- But if you get the date after initializing the
FormGroup, you can keep your initialization as is it, then patch the data comes from the API like the following:
onDataReceived(person) {
this.personForm.patchValue({
firmenBez: person.firmenbezeichnung,
});
}
Answered By - Amer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.