我有一个带有一些输入的引导模态,我想清除它,如果单击取消按钮,模态关闭。如果我刷新页面,它显然会重置,但我只是希望能够在表单字段中输入一些数据,单击取消按钮并立即关闭模态,然后一旦关闭,单击再次打开模式并拥有表格字段为空。
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog bodyWidth">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add Data Point</h4>
</div>
<div class="modal-body">
<form class="form-inline" [formGroup]="modalForm" (ngSubmit)="submitForm(modalForm.value)">
<div class="row">
<div class="form-group" [ngClass]="{'has-error':!modalForm.controls['dataPoint'].valid && modalForm.controls['dataPoint'].touched}">
<label>Data Point:</label>
<input class="form-control special" type="text" class="form-control special" placeholder="Enter a data point" [formControl]="modalForm.controls['dataPoint']">
</div>
<div class="form-group" [ngClass]="{'has-error':!modalForm.controls['ICCP'].valid && modalForm.controls['ICCP'].touched}">
<label >ICCP:</label>
<input type="text" class="form-control special" placeholder="Enter an ICCP" [formControl]="modalForm.controls['ICCP']">
</div>
<div class="form-group" [ngClass]="{'has-error':!modalForm.controls['startDate'].valid && modalForm.controls['startDate'].touched}">
<label>Start Date:</label>
<input class="form-control special" type="text" placeholder="Select a start date" [formControl]="modalForm.controls['startDate']" style="margin-right: 4px;">
</div>
<div class="form-group" [ngClass]="{'has-error':!modalForm.controls['endDate'].valid && modalForm.controls['endDate'].touched}">
<label >End Date:</label>
<input type="text" class="form-control special" placeholder="Enter an end date" [formControl]="modalForm.controls['endDate']">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<div style="float: left;">*All Fields Are Required</div>
<button type="submit" class="btn" [disabled]="!modalForm.valid" data-dismiss="modal">Add</button>
<button type="submit" (click)="resetForm()" class="btn" data-dismiss="modal" ng-click>Cancel</button>
</div>
</div>
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'add-validation',
styleUrls: ['../app/app.component.css'],
templateUrl: 'add.component.html'
})
export class AddComponent {
modalForm : FormGroup;
constructor(fb: FormBuilder){
this.modalForm = fb.group({
'dataPoint' : [null, Validators.required],
'ICCP' : [null, Validators.required],
'startDate' : [null, Validators.required],
'endDate' : [null, Validators.required]
})
console.log(this.modalForm);
this.modalForm.valueChanges.subscribe( (form: any) => {
console.log('form changed to:', form);
}
);
}
submitForm(value: any){
console.log(value);
}
resetForm(){
this.modalForm = new FormGroup();
}
}
答案 0 :(得分:1)
FormGroup
有一个名为reset()
的方法:
this.modalForm.reset();
您可以在Angular 2 official documentation中详细了解reset()
和FormGroup
。