Home > Enterprise >  Create single instance of reactive form in Angular
Create single instance of reactive form in Angular

Time:11-17

I have defined a separate form component where I am creating a reactive form. I am calling that component in another component. Since, I want to use the form twice, I want to create one instance of it. So, that anything that user changes on one form gets changed in another as well. I am calling my form component in a single template. So, I want single instance to be created of it.

Here's my code:

main.component.html

<shop-form></shop-form>

//some code

<shop-form
  (eventEmitter)="getEventData($event)"
></shop-form>

form.component.ts

 this.form = new FormGroup({
  name: new FormControl(null, Validators.required),
  address: new FormControl(null, Validators.required),
  no: new FormControl(null, Validators.required),
  code: new FormControl(null, Validators.required),
  instructions: new FormControl(null),
});

Any help would be appreciated. Thanks

CodePudding user response:

If the intention is showing the same form or HTML content at two places only then no need to create any child component or make a single instance of a form... Use ng-template instead...

This way (put your form HTML code inside ng-template) -

<ng-template #reusableTemplate>
Html content which is going to be reused in component
</ng-template>

And then show the same content as many places as you want, this way -

<ng-container *ngTemplateOutlet="reusableTemplate">
</ng-container> 
 <p> Some text </p>
<ng-container *ngTemplateOutlet="reusableTemplate">
</ng-container> 
  • Related