Angular-如何从父组件访问嵌套子组件

时间:2019-01-10 09:37:49

标签: typescript tabs angular6 parent-child

我下面有以下代码段:

AppComponent.component.html

<section class="tabs">
    <tab-set [heading]="'Discover'">
       <tab-content [title]="'Profile'" [paneId]="panel01">
       </tab-content>
       <tab-content [title]="'Follow'" [paneId]="panel02">
       </tab-content>
       <tab-content [title]="'Contact'" [paneId]="panel03">
       </tab-content>
    </tab-set>
</section>

TabsetComponent.ts

@Component({
   selector: 'tab-set',
   template: 
   `
   <div class="tab-set">
      <h2 class="d-flex tab-set-title">{{heading}}</h2>
      <ul class="tab-list">
          <!-- I want to access all children <tab-content> and get title to render it here -->
          <li class="tab-item"></li>
      </ul>
   </div>

   <div class="tab-content>
        <!-- I want to access html of each child <tab-content> to render it here -->
   </div>
   `
})
export class TabsetComponent implements OnInit, AfterViewInit, AfterContentInit {
   @Input() heading: string;
   @ContentChildren(TabContentComponent) contentTabs;
   @ViewChildren(TabContentComponent) viewTabs;

   ngOnInit() {

   }

   ngAfterViewInit(): void {
      // contentTabs still null
      // viewTabs still null
   }
   ngAfterContentInit(): void {
      // contentTabs still null
      // viewTabs still null
   }
}

TabContentComponent.ts

@Component({
   selector: 'tab-content',
   templateUrl: './tab-content.component.html',
   styleUrls: ['./tab-content.component.scss']
})
export class TabContentComponent implements OnInit {

  @Input() title: string;
  @Input() paneId: string | number;

  constructor() { }

  ngOnInit() { }

}

根据代码,如何在TabsetComponent中获得全部信息。我尝试使用ViewChildren和ContentChildren,但似乎无法正常工作。请帮助解决它,谢谢。

更新2019/01/11

我已经将TabsetComponent注入TabContentComponent的构造函数中,然后将每个tabcontent添加到数组的tabs属性中。但是在UI上仍然无法呈现视图TabContentComponent。

export class TabsetComponent implements OnInit, AfterViewInit, AfterContentInit {
   private tabs: TabContentComponent[];

   // ... the others line code

   addTab(tabContent: TabContentComponent) {
     this.tabs.push(tabContent);
   }

}


export class TabContentComponent implements OnInit {

   @Input() title: string;
   @Input() paneId: string | number;

   constructor(private tabset: TabsetComponent) { }

   ngOnInit() {
      this.tabset.addTab(this);
   }
}

0 个答案:

没有答案