Re-Use Angular 2 Form Components

I am currently working on an Angular project and would like to be able to reuse my form components for both the creating and updating of entities.

For example, I have a User entity on a remote API and I have a form on the front end that allows me to create these users and POST the input to the server. This works great!

The issue begins when trying to use the same form for updating. I need to fill the form input fields with the stored information from the remote server by making a GET request. The issue is that the form component loads before the REST request Observable responds with the User entity.

How can I fill a form with information from a remote server before the form is fully loaded?

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

The easiest way is to use ngIf

@Component({
  selector: 'xxx',
  template: `
<form *ngIf="model">
  ...
</form>

<!-- optional -->
<my-spinner *ngIf="!model"></my-spinner>
`})
export class MyComponent {
  constructor(private myService:MyService) {
    this.myService.getData.subscribe(data => this.model = data);
  }
}

then *ngIf adds the form to the DOM as soon as this.model = data is executed.