Reputation: 1313
I'm creating a form with input fields. There are some default inputs fields values that come from a REST API.
Here is my template :
<form [formGroup]="form" (ngSubmit)="action()">
<input type="text" formControlName="name" [value]="fromApi(name)">
</form>
And my TS code :
this.form = new FormGroup({name:new FormControl('')})
The client got his default value from the API. He can change that data in the input field.
There are two possibilities :
1) He does change the initial value coming from the API. In that cas when I console.log the FormGroup, I got the new value he entered, that's perfect !
2) He doesn't want to change the value from the API. And that's my problem : in that case, the value for the input name is '' (the value from FormControl). And I would like to have the value from the API.
Is it possible ? Thanks
Upvotes: 1
Views: 439
Reputation: 3574
You can try this:
ngOnInit(){
this.form = new FormGroup({name:new FormControl('')});
this.fromApi();
}
fromApi(){
//inside the subscribe method of the api called
let valueFromAPI = 'Example';
this.form.controls.name.setValue(valueFromAPI);
}
or
this.fromApi('name');
fromApi(control){
//inside the subscribe method of the api called
let valueFromAPI = 'Example';
this.form.controls[control].setValue(valueFromAPI);
}
Upvotes: 0
Reputation: 15221
sure it is.
fire your method to fetch from api in components ngOnInit
hook and once you get data back (in subscribe, i guess) patchValue
of the formControl.
Upvotes: 1