Abel Valdez
Abel Valdez

Reputation: 2408

Angular 5 group FormBuilder with filling default values from Observable or Promise

I'm trying to develop a form in angular 5 with default values coming from an API service I just trying to assign the default value when the formbuilder is been initialized. I got the same result if i use subscribe() or toPromise()

Component.ts

settingsForm: any;

 constructor(
  private userService: UserService,
  private settingsService: SettingsService,
  private formBuilder: FormBuilder
 ) { }  

ngOnInit() {
    this.settingsService.getMetrics$()
    .toPromise().then(res =>{
      this.settingsForm = this.formBuilder.group({
        oee: [res.oee, Validators.required],
        fpy: [res.fpy, Validators.required],
        difsites: [res.difsites, Validators.required]
      });
    })
  }

HTML template

 <form [formGroup]="settingsForm" (ngSubmit)="onSubmit()" style="margin-top: 15px">

                <div class="form-group">
                    <label for="oee">OEE:</label>
                    <input id="oee" class="form-control" type="text" formControlName="oee">
                </div>

                <div class="form-group">
                    <label for="fpy">FPY:</label>
                    <input id="fpy" class="form-control" type="text" formControlName="fpy">
                </div>

                <div class="form-group">
                    <label for="difsites">Diff. Sites:</label>
                    <input id="difsites" class="form-control" type="text" formControlName="difsites">
                </div>

                <button type="submit" [disabled]="!settingsForm?.valid" class="btn btn-primary">Save</button>
            </form>

But like that i receiving a console error because settingsForm is null.

ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

Upvotes: 0

Views: 844

Answers (2)

PeS
PeS

Reputation: 4039

As itsundefined pointed out the form is not defined when the template is rendering.

The simplest solution would be to define the form with

<form *ngIf="settingsForm" [formGroup]="settingsForm" (ngSubmit)="onSubmit()" style="margin-top: 15px">

See the ngIf there.

Upvotes: 2

itsundefined
itsundefined

Reputation: 1450

This happens because you are not waiting for the response from the backend to create the HTML elements that point to that still undefined formGroup. What you need to do is create an empty form synchronously and then update it with values, when the backend finally responds, using the setValue method. Alternatively you can add a boolean let's say named loaded to your component that is true when the server has responded and then use *ngIf="loaded" on your html form.

Upvotes: 1

Related Questions