Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda