Pass data to nth level child component in Angular 4

前端 未结 2 1802
眼角桃花
眼角桃花 2021-01-24 01:12

Below is my structure of components in Angular application,

  • app.component.html

  • units.component.html

  • sectio

2条回答
  •  执念已碎
    2021-01-24 02:02

    For this scenario you can use a shared service to communicate between components.

    create a shared service like this.

    @Injectable()
    export class SharedDataService {
    
      public set appData(data: any) {
         this._appData = data;
      } 
    
      public get appData(): any {
         return this._appData;
      }
    }
    

    And then inject the SharedDataService to the app.component. And set the appData to the service.

    app.component.ts

    constructor(private sharedDataService: SharedDataService) {
    
    }
    
    public setAppData(): void {
      this.sharedDataService.appData = this.appData;
    } 
    

    And inject the SharedDataService to the app-section.component then you can get the appData from the service.

    app-section.component.ts

    constructor(private sharedDataService: SharedDataService) {
    
    }
    
    public getAppData(): void {
       this.appData = this.sharedDataService.appData;
    }
    

    Then you can access the appData in the template like this.

    app-section.component.html

    {{appData}}
    

    There are various ways to communicate between components in angular. And that is called Component interaction. you can read more about this in the angular official documentation. Component Interaction

提交回复
热议问题