角反应式表单按钮单击事件

时间:2018-07-16 07:41:07

标签: angular angular-reactive-forms

我想使用反应性表格方法按角度创建完整的动态表格。

您能否帮助我创建一个带有按钮,日期控件和下拉列表的表单组,以及如何将事件与每个控件相关联。

假设在我的表单中有5个按钮,如何将不同的事件绑定到每个按钮。

2 个答案:

答案 0 :(得分:1)

如下使用。当您在窗体上的任何地方单击时,将触发此操作。 HTML:

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

TS:

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

答案 1 :(得分:0)

您可以参考此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);
  }
}