I\'d like to know the best way to do this, and if there are different ways. I\'m trying to call a function in a child component from its parent component. So if I have:
Well the other answers are just correct, but I think some times that function is supposed to be called with the flow of the data the angular way from parent to child, so what you actually need is to run a function every time a variable has changed in the parent component. see below:
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
variable = "yes!";
toggle() {
this.variable = this.variable === "yes!" ? "hell no!" : "yes!";
}
}
app tempalte:
Parent says: {{variable}}
child component:
export class ChildComponent implements OnInit {
_childVar: string; // if you need to record the value and access later in child component
counter = 0;
@Input()
set childVar(value: string) {
this._childVar = value;
this.childFunction(); // the answer is here
}
childFunction() {
this.counter++;
console.log("called child function");
}
}
test here https://stackblitz.com/edit/angular-1rywfc