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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
}

5 Comments

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 !
From whichever API you get the value, inside its subscribe function you can use the setValue method of your form.
You can even make it dynamic. See the updated solution.
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.