简体   繁体   中英

angular reactive Form Button click event

I would like to create complete dynamic Form in angular with reactive Form approach.

Could you help me to create a form group with a button, a date control and a drop down list as well as how to associate events to each control .

Suppose in my form 5 buttons are there ,how to bind different events to each button.

Use this as below. This will trigger when you click everywhere on the form. HTML:

<form [formGroup]="myForm" (click)="clickedMe()">
</form>

TS:

clickedMe(){
  alert("clicked me");
}

You can refer this example

HTML:

<form [formGroup]="basicForm" (ngSubmit)="submit()" novalidate autocomplete="off">
    <div>
        <label>Enter Text: </label>
        <input placeholder="Enter Text" formControlName="userText" />
    </div>
    <div>
        <label>Select Date:  </label>
        <input type="date" (change)="dateChange($event)" placeholder="select date" formControlName="userDate">

        <label>  Selected Date:  {{basicForm.get('userDate').value}}</label>
    </div>

    <div>
        <label>Enter Number: </label>
        <input placeholder="Enter Text" formControlName="userNum" />
    </div>

    <div>
        <select formControlName="gender">
      <option *ngFor ="let gen of dropDown">
        {{gen}}
      </option>
    </select>
    </div>

    <div>
        <button type="submit" [disabled]="!basicForm.valid">Submit Form</button>
    </div>

    <div>
        <button (click)="basicForm.reset()">Clear Form</button>
    </div>
</form>
<div *ngIf="basicForm.valid">
    Form Data: {{basicForm.value | json}}

</div>

TS:

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

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

  dropDown: Array<any> = [
    'Male', 'Female', 'Others'
  ]

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.basicForm = this.fb.group({
      userText: [null, Validators.required],
      userNum: null,
      userDate: [null, Validators.required],
      gender: ['Male', Validators.required],
    })
  }

  dateChange(event) {
    console.log(event);
    this.basicForm.get('userDate').setValue(event.target.value)
  }

  submit() {
    console.log(this.basicForm.value);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM