I am facing bit confusion to reset a field in child component from parent. I'm having a field in child component, when calling a function in parent component the child field should reset. Child component:
@Component({
selector: 'my-app',
template: `
<input type="text" placeholder="Type your name..." [formControl]="Name"/>
`})
export class ChildComponent {
Name = new FormControl('');
}
Parent component:
@Component({
selector: 'my-parent-app',
template: `
`})
export class ParentComponent {
resetName(){
// Here I need to reset my child component field..
}
}
If any one have idea, could you please help me to understand..
If you access the child through its selector within the template you can set up a @ViewChild to gain access to its class which would look like below for the following example, using its class for the type. Be sure to import @Viewchild
and ChildComponent
.
@Component({
selector: 'my-parent-app',
template: `
<my-app #component-child></my-app>
`})
export class ParentComponent {
@ViewChild('component-child') childComponent: ChildComponent;
public resetName(): void
{
console.log(this.childComponent) // should see everything within the class.
this.childComponent.name.reset(); // should reset the form in child component
}
}
Drop a comment if you face any trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With