Angular 2 Sibling Component Communication

前端 未结 12 1489
深忆病人
深忆病人 2020-11-22 06:31

I have a ListComponent. When an item is clicked in ListComponent, the details of that item should be shown in DetailComponent. Both are on the screen at the same time, so

12条回答
  •  梦如初夏
    2020-11-22 07:10

    You need to set up the parent-child relationship between your components. The problem is that you might simply inject the child components in the constructor of the parent component and store it in a local variable. Instead, you should declare the child components in your parent component by using the @ViewChild property declarator. This is how your parent component should look like:

    import { Component, ViewChild, AfterViewInit } from '@angular/core';
    import { ListComponent } from './list.component';
    import { DetailComponent } from './detail.component';
    
    @Component({
      selector: 'app-component',
      template: '',
      directives: [ListComponent, DetailComponent]
    })
    class AppComponent implements AfterViewInit {
      @ViewChild(ListComponent) listComponent:ListComponent;
      @ViewChild(DetailComponent) detailComponent: DetailComponent;
    
      ngAfterViewInit() {
        // afther this point the children are set, so you can use them
        this.detailComponent.doSomething();
      }
    }
    

    https://angular.io/docs/ts/latest/api/core/index/ViewChild-var.html

    https://angular.io/docs/ts/latest/cookbook/component-communication.html#parent-to-view-child

    Beware, the child component will not be available in the constructor of the parent component, just after the ngAfterViewInit lifecycle hook is called. To catch this hook simple implement the AfterViewInit interface in you parent class the same way you would do with OnInit.

    But, there are other property declarators as explained in this blog note: http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/

提交回复
热议问题