Home > OS >  Multilevel data passing in Angular
Multilevel data passing in Angular

Time:11-30

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.

CodePudding user response:

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

  • Related