angular – 从父组件重置表单

前端之家收集整理的这篇文章主要介绍了angular – 从父组件重置表单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个组件,我有模块弹出窗口,其中包含子组件:

<modal data-backdrop="static" #modalTask (onDismiss)="modalTask.close()" [size]="'lg'">
    <modal-header>
        <h4 style="color:#fff">Add CRL Task</h4>
    </modal-header>
    <modal-body>
        <TaskComponent [isReset] ="resetForm" #tasks></crlTask>
    </modal-body>
    <modal-footer>
        <button type="button" class="btn btn-primary" (click)="onTaskClick();">Create</button>
        <button type="button" class="btn btn-default" data-dismiss="modal" (click)="modalTask.close();">Cancel</button>
    </modal-footer>
</modal>

现在那个子组件如下:

<form #taskForm="ngForm" name="rplForm">
 //Contains Input Controls 
</form>

编辑

由于得到了一个解决方案,我将重置放在子组件的ngOnChanges中.这是Child组件的代码

taskForm: FormGroup;
@Input() isReset: boolean = false;

ngOnChanges() {
        if (this.isReset) {
              this.rplForm.reset();
        }
    }

现在我在onTaskClick()上保存taskForm,我能够这样做.我无法做的是重置子组件下的表单.

我尝试使用reset()但是无法这样做.我可以从父组件中使用哪些东西?

解决方法

根据您使用ngOnChanges提供的更新,您需要在使用模板驱动表单时使用NgForm指令. rplForm不是FormGroup,你甚至不需要它,因为它属于反应形式.所以你要引用的是taskForm并重置它. rplForm在这里是多余的.

您需要导入ViewChild才能引用您的表单,然后在表单上调用reset:

import { ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

//...

@ViewChild('taskForm') myForm: NgForm;

ngOnChanges() {
  if (this.isReset) {
     this.myForm.reset();
  }
}

猜你在找的Angularjs相关文章