millimoose
millimoose

Reputation: 39950

How can I associate a button with a form using Angular?

I'm working with Angular 6.x, and I'd like to associate a submit button located outside the form in the DOm with it. That is, I want to accomplish something structurally equivalent to this:

<button type='submit' form='myform'>
  click me!
</button>

<form id='myform' action='#' onsubmit='console.log("wheee")'>
  <input type='submit' value='me too'/>
</form>

I.e. I want to handle the submit event from the form element.

Is there a way to do this without going through nativeElement or without moving/duplicating the submit handler on the click event of the button?

Upvotes: 0

Views: 1863

Answers (3)

SiddAjmera
SiddAjmera

Reputation: 39432

Well, you could use a Reactive Form and then on the click of this button. call a function that would extract the value of the form and do something on it.

This way, you can also do things like disabling the button if the form is invalid.

So here's what your form will look like:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  userForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.userForm = this.fb.group({
      firstName: [, Validators.required],
      lastName: [, Validators.required]
    });
  }

  submitForm() {
    console.log('Form Submitted with value: ', this.userForm.value);
  }
}

And here's the template:

<h3>User Form</h3>
<hr>
<form [formGroup]="userForm">
  <div>
    <label for="firstName">First Name: </label>
    <input type="text" id="firstName" formControlName="firstName">
  </div>
  <br>
  <div>
    <label for="lastName">Last Name: </label>
    <input type="text" id="lastName" formControlName="lastName">
  </div>
</form>
<br>
<button (click)="submitForm()" [disabled]="userForm.invalid">Submit</button>

Here's a Sample StackBlitz for your ref.

Upvotes: 0

Gabriel Lopez
Gabriel Lopez

Reputation: 452

Tyr it like this.

<button type='submit'  (click)="myForm.submit()">
  click me!
</button>

<form id='myform' action='#' #myForm onsubmit='console.log("wheee")'>
  <input type='submit' value='me too'/>
</form>

Upvotes: 1

Sunil
Sunil

Reputation: 11243

You can achieve by reference #form of form and passing the same reference to button.

<button type='button' (click)="form.onsubmit()">
  click me!
</button>

<form id='myform' #form action='#' onsubmit='console.log("wheee")'>
  <input type='submit' value='me too'/>
</form>

Working copy is here - https://stackblitz.com/edit/angular-pnneks

Upvotes: 1

Related Questions