David
David

Reputation: 4508

Get data from some function and use it as default values of arguments of formModel

In my Angular component I have

import { NgForm } from '@angular/forms';

export class ProfileComponent implements OnInit {
  userProfile;
  formModel={
    FirstName:"",
    LastName:""
  }

And in ngOnInit I have function that gets data

  ngOnInit() {
this.service.getUserProfile().subscribe(
  res => {
    this.userProfile = res;

What I want is to use that data as default valuse of formModel. Is that possible ? and how ?

Upvotes: 0

Views: 96

Answers (1)

abhay
abhay

Reputation: 127

ngOnInit() {
this.service.getUserProfile().subscribe(
  res => {
    this.userProfile = res;

In your ngOnInit you have assigned the response to the userProfile.Now you what this data to be displayed on your template. So there is three ways in which yo can do this particular process:

Option 1: use a flag which you can turn on and off

  ngOnInit() {
      this.formReadyFlag = false;
      this.service.getUserProfile().subscribe(
          res => {
             this.userProfile = res;
             this.formReadyFlag = true;
      })
}

correspondingly in your html you will render the form only after the response is retrieved from the server.

component.html

<input [(formModel)]="userProfile?.name" *ngIf="formReadyFlag"/>

Option 2: ensure that the response which is being assigned has a new reference so that change detection is triggered.

  ngOnInit() {
      this.service.getUserProfile().subscribe(
          res => {
             this.userProfile = {...res};// shallow cloning to ensure a new reference is formed and assigned to the class variable.
      })
}

this option is a less tedious approach to the earlier option.

Option 3: make use of observables and async pipe that way you have less boilerplate code to write and everything works seamingly.This method cannot be used in case you want to perform some operation on the response.

component.ts

    this.userProfile$ = Observable<any> | Subscription<any>;// Depends on the response type of the service method.   
ngOnInit() {
          this.userProfile$ = this.service.getUserProfile();
    }

component.html

<input [(formModel)]="(userProfile | async)?.name"/>

Upvotes: 1

Related Questions