Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
      }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading