Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Communicating child class to Parent class - right way

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)
    );
  }
}

Live Demo

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!