1

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

AntonBoarf
  • 1,239
  • 15
  • 31
  • NOT use [value], take a look at https://stackoverflow.com/questions/48337798/angular-reactive-form-cannot-set-property-of-undefined?rq=1 and use a function to fill the form – Eliseo Jun 21 '18 at 11:17

2 Answers2

1

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.

dee zg
  • 13,793
  • 10
  • 42
  • 82
0

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);
}
Prachi
  • 3,478
  • 17
  • 34
  • Thanks. Your solution works but my example is pretty easy. My real form is really complex with plenty API calls from different URLs. I wish I could find a solution without any code ! – AntonBoarf Jun 21 '18 at 11:26
  • From whichever API you get the value, inside its subscribe function you can use the setValue method of your form. – Prachi Jun 21 '18 at 11:28
  • You can even make it dynamic. See the updated solution. – Prachi Jun 21 '18 at 11:28
  • Normally you get from API an object and you want to reflect the data in your form. I don't understand use setValue, better give values when you create the FormControl – Eliseo Jun 21 '18 at 13:36
  • In case of multiple API calls for fetching the values, you cannot wait for the response of all the APIs in a synchronous way and then create a form. And you have to manage the same for add and edit functionality. – Prachi Jun 22 '18 at 05:55