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

193
Visualizações
Multilevel data passing in Angular

Suppose you have a parent component A and inside of it you have some variable x. You would like to pass this variable to the child component B. Easy! Just use @Input annotation and call it a day. But what if B has another child component C? How would we pass x from A to C? I tried using the same approach to pass it from B to C, but it only passes the value undefined.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a common service file which is data.service.ts file in this case. This service will be injected by both the parent and grand child. When component A which is grand parent here want to send a data it will call the deliverMsg method of the data service file. The component C which is grand child will listen to this change by injecting the same data.service

data.service.ts

// relevant imports

    @Injectable()
    export class DataService {

      private message = new BehaviorSubject('default message');
      portMessage = this.message.asObservable();

      constructor() { }

      deliverMsg(message: string) {
        this.message.next(message)
      }

    }

parent.component.ts

 //all relevant imports

    @Component({
      selector: 'app-parent-a',
      template: 'html file url',
      styleUrls: ['./sibling.component.css']
    })
    export class ParentComponent implements OnInit {

      message:string;
      constructor(private data: DataService) { }

      ngOnInit() {
        
      }
      
      newMessage() {
        this.data.deliverMsg("Hello from Grand Parent")
      }

    }

grandchild.component.ts

// all relevant imports

    @Component({
      selector: 'app-sibling',
      template: 'template',
      styleUrls: ['./sibling.component.css']
    })
    export class SiblingComponent implements OnInit {

      message:string;

      constructor(private data: DataService) { }

      ngOnInit() {
        this.data.portMessage.subscribe(message => this.message = message)
      }
}

Alternatively you can also you NgRx

about 4 years ago · Juan Pablo Isaza Relatório
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