I just can't understand,
How to call a function inside child component when clicking on the button in the parent component?
I just can't understand,
How to call a function inside child component when clicking on the button in the parent component?
Make use of @ViewChild
decorator to get access to your child component.
import { ChildComponent } './child.component'
import { ViewChild } from '@angular/core';
export class ParentComponent {
@ViewChild(ChildComponent)
childComponent: ChildComponent;
someMethod() {
this.childComponent.someFunction();
}
}
If this is your parent template:
<button (click)="onClick()">Click</button>
<div>
<child-component></child-component>
</div>
You can use @ViewChild()
in the parent:
export class ParentComponent {
@ViewChild(ChildComponent)
child: ChildComponent;
onClick(): void {
if (this.child) {
this.child.someFunction();
}
}
}
Another way would be to do it in the template directly:
You can change your template to this:
<button (click)="child.someFunction()">Click</button>
<div>
<child-component #child></child-component>
</div>
Then there is no need to use @ViewChild. You can even pass the child variable to a function inside your parent, if you need to do additional stuff in the click
Use the ViewChild decorator. https://alligator.io/angular/viewchild-access-component/#child-components It's simple ;)
As the others say, you can use @ViewChild. But notice that this way you will call the function on the first child of that type. If you have a child component like this:
@Component({
selector: 'app-my-child',
template: '<p>I am the child number {{id}} </p>'
})
export class MyChildComponent {
@Input() id: number;
constructor() { }
print() {
console.log('Action from id ' + this.id);
}
}
and a parent component like this:
<button (click)="printChild()">Print!</button>
<app-my-child [id]="1"></app-my-child>
<app-my-child [id]="2"></app-my-child>
referenced by
@Component({
selector: 'app-internal',
templateUrl: './internal.component.html'
})
export class InternalComponent {
@ViewChild(MyChildComponent) child: MyChildComponent;
constructor() { }
printChild() {
this.child.print();
}
}
you will always call the print function of the first element found. So, if you swap the two MyChildComponents you will have "Action from id 2" printed.
To avoid it you can explicitly identify the target component like this:
<button (click)="id2.print()">Print!</button>
<app-my-child #id1 [id]="1"></app-my-child>
<app-my-child #id2 [id]="2"></app-my-child>
if you don't want to reference them in the component class or use the opposite approach:
@ViewChild('id1') child1 : MyChildComponentComponent;
printChild() {
this.child1.print();
}