In my angular app, I am trying to communicate model class in to parent class by passing a function as a parameter. but end up with error.
some reason, if the model class required to communicate with it's parent, what is the correct way?
here is my try:
import { Component, OnInit } from "@angular/core";
class PropsData {
public productName: string;
private _value: number;
private _count: number;
parentLink: () => void;
public get value() {
return this._value;
}
public set value(value) {
this._value = value;
this.details = this._value * this._count;
}
public get count() {
return this._count;
}
public set count(value) {
this._count = value;
this.details = this._value * this._count;
this.parentCommunicator(this.parentLink);
}
details: number;
parentCommunicator(parentHook) {
parentHook(); //4 trying to call
}
constructor(
name: string,
value: number,
count: number,
parentHook: () => void
) {
this.productName = name;
this.count = count;
this.value = value;
this.parentLink = parentHook; 3//assigning
}
}
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
products: PropsData[];
allTotal: number = 0;
parentHook(): void { //1 need to called from child
alert("parent called");
}
ngOnInit() {
this.products = [
new PropsData("sugar", 20, 1, this.parentHook), //2. passing as a param
new PropsData("salt", 40, 1, this.parentHook),
new PropsData("jackery", 70, 1, this.parentHook)
];
this.updateAllTotal();
}
updateCount(product: PropsData): void {
product.count++;
this.updateAllTotal();
}
updateAllTotal(): void {
this.allTotal = 0;
this.products.forEach(
(item) => (this.allTotal = this.allTotal + item.details)
);
}
}