Juliatzin
Juliatzin

Reputation: 19695

Is it possible to separate <form> tag from component

I have a form component that I use in 2 differents places. The only difference is that they belongs to differents forms.

So, I tried to extract tag from component, and now I have

<form (ngSubmit)="onSubmit()">
    <app-my-component-with-inputs></app-my-component-with-inputs>
</form>

If I keep the form inside the component, I will have:

My Component

<form "name"="mycomponent">
  <input1>
  <input2
  <input3...>
</form>

First Usage of my component

<app-my-component-with-inputs></app-my-component-with-inputs>

Everything is fine for the first usage.

But for the second usage, the component is already inside a bigger form, so with the form inside, I will have :

<form name="form2">
  <input3>
  <input4>
  <input5>
  <!-- if I put <form> tag inside the component, I will have 2 <form> in my second usage -->
  <app-my-component-with-inputs></app-my-component-with-inputs> 
</form>

But then, when I click submit button, inside component, it doesn't trigger the onSubmit Method ( which I understand, as it is not anymore part of the component)

How should I do to trigger the onSubmit() method ?

Is it ok to do this, or is there a better way?

Upvotes: 1

Views: 88

Answers (2)

Hiren Shah
Hiren Shah

Reputation: 326

For common controls, I think you should create a custom component implementing ControlValueAccessor as below:

https://medium.com/@tarik.nzl/angular-2-custom-form-control-with-validation-json-input-2b4cf9bc2d73

so you can use as below:

component1.html

<form (ngSubmit)="onSubmit()">
    <app-my-component-with-inputs [(ngModel)]="model"></app-my-component-with-inputs>
    <button type="submit"></button>
</form>

component1.ts

onSubmit() {
    // use form model
}

component2.html

<form (ngSubmit)="onSubmit2()">
    <input [(ngModel)]="model.data1" name="data1">
    <input [(ngModel)]="model.data2" name="data2">
    <input [(ngModel)]="model.data3" name="data3">
    <app-my-component-with-inputs [(ngModel)]="model.submodel"></app-my-component-with-inputs>
    <button type="submit"></button>
</form> 

component2.ts

onSubmit2(data) {


}

Upvotes: 0

Hiren Shah
Hiren Shah

Reputation: 326

Considering that you need to show same form on multiple pages, you can take form tag inside your component, now to trigger onSumit function use @output as follows:

Main component1 ts file add

@Output('onSave') onSave = new EventEmitter();
onSubmit() {
    this.onSave.emit(this.model);   // model hold your form model data
}

Main component1 html file

<form (ngSubmit)="onSubmit()">
...
</form>

component1.html

<app-my-component-with-inputs (onSave)="onSubmit($event)"></app-my-component-with-inputs>

component1.ts

onSubmit(data) {
    // use form data
}

component2.html

<app-my-component-with-inputs (onSave)="onSubmit2($event)"></app-my-component-with-inputs>

component2.ts

onSubmit2(data) {
    // use form data
}

Upvotes: 1

Related Questions