Reset form from parent component
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();
}
}
The Hungry Dictator
Developer by Profession, Cook / Traveler / Photographer by Passion. Reach me : Github , LinkedIn , Facebook , Twitter
Updated on June 09, 2022Comments
-
The Hungry Dictator almost 2 years
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 componenttaskForm: FormGroup; @Input() isReset: boolean = false; ngOnChanges() { if (this.isReset) { this.rplForm.reset(); } }
Now I am saving
taskForm
ononTaskClick()
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? -
The Hungry Dictator about 6 yearsOther than using services?
-
The Hungry Dictator about 6 yearsNot happening. Tried it
-
Nour about 6 yearsStrange, did you implement OnChanges on your child component ?
-
The Hungry Dictator about 6 yearsI did check it and it goes inside the
ngOnChanges
as well but still not happening -
Nour about 6 yearsCould you apply the inside the ngOnChanges please
-
The Hungry Dictator about 6 yearsUpdated the question please check
-
The Hungry Dictator about 6 yearsYes I am using reactive form
-
The Hungry Dictator about 6 years
rplForm
istaskForm
. That was a mistake that I have updated. -
The Hungry Dictator about 6 yearsAlthough I tried it yesterday it was not working, But somehow started working today. Maybe I was doing something wrong. Thanks for the answer
-
AT82 about 6 yearsMaybe some magic happened over night :D Well, but glad to hear you got it working :)
-
The Hungry Dictator about 6 yearsSeems like that so. :D