簡體   English   中英

角度動態的孩子與父母的交流

[英]Angular dynamic child to parent communication

我正在構建一個應用程序,其中一個模塊加載一個共享的全局組件以及一個由路由器驅動的子組件。 當模塊加載子級時,它應該接收數據並將其發送到全局組件。

如何從動態加載的子組件中檢索數據?

全局組件:

零件:

export class global__component implements OnInit {
  constructor() { }

  // bring data from other components
  @Input() pageTitle: string;

  ngOnInit() {
  }
}

HTML:

<p>{{pageTitle}}</p>

模塊組件:

零件:

export class parent__component OnInit {
  constructor() { }

  // bring data from other components
  @Input() pageTitle: string;

  ngOnInit() {
  }
}

HTML:

<global-component [pageTitle]="pageTitle"></global-component>
<router-outlet></router-outlet>

子組件一:

零件:

export class child_component_one implements OnInit {
  constructor() { }

  // send data to other components
  @Output() pageTitle: string = 'Child component One title';

  ngOnInit() {
  }
}

子組件二:

零件:

export class child_component_two implements OnInit {
  constructor() { }

  // send data to other components
  @Output() pageTitle: string = 'Child component two title';

  ngOnInit() {
  }
}

@Josavish的評論使我轉向路由器搜索答案,並偶然發現了此帖子,其中包含我需要的一些代碼。

父組件:

零件:

export class parent__component implements OnInit {
  constructor() { }

  // set default value
  pageTitle: string = '';

  // get data from children components
  setData(data){
    this.pageTitle = data.updateComponentData().pageTitle;
  }

  ngOnInit() {
  }

}

HTML:

<global-component[pageTitle]="pageTitle"></global-component>
<router-outlet (activate)="setData($event)"></router-outlet>

子組件:

零件:

export class child__component implements OnInit {
  constructor() { }

  // set page title
  pageTitle: string = 'Child component title';

  // update parent component data
  updateComponentData(){
    return {
      pageTitle: this.pageTitle
    }
  }

  ngOnInit() {

  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM