Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset form from parent component

I have one component under which I have modal popup which contains child component :

<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>

Now that child component is as follows :

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

EDIT

As got one solution I have put reset inside ngOnChanges of child component. Here is the code from Child component

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

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

Now I am saving taskForm on onTaskClick() and I am able to do so. What I am not able to do is to resetting the form which is under child component.

I tried using reset() but was not able to do so. Anything using which I can do so from parent component?

like image 617
The Hungry Dictator Avatar asked Feb 08 '18 08:02

The Hungry Dictator


1 Answers

Based on the update you have provided with ngOnChanges is that you need to use the NgForm directive as you are using a template driven form. rplForm is not a FormGroup, you don't even need it here, as that belongs with reactive forms. So what you want to reference is taskForm and reset that. rplForm is redundant here.

You need to import ViewChild to be able to reference your form, then call reset on your form:

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

//...

@ViewChild('taskForm') myForm: NgForm;

ngOnChanges() {
  if (this.isReset) {
     this.myForm.reset();
  }
}
like image 137
AT82 Avatar answered Nov 04 '22 08:11

AT82