簡體   English   中英

Angular 6:訪問子組件的子組件(來自父組件)

[英]Angular 6: Access to child of child component (from parent one)

如何訪問(調用某些方法)某個父(容器)組件的(2)子組件的子組件; 即,讓ParentCmp在模板內部包含兩個子組件(它們的選擇器 + 模板引用),並在這些(兩個子)組件中調用LoadingPanels某些方法:

ParentCmp.html : ....

<child1 #child1></child1>
<child2 #child2></child2>

ParentCmp.ts

  @ViewChild('child1', read: ComponentRef<child1Cmp>) child1Cmp: ComponentRef<InvitationsBarComponent>;
  @ViewChild('child2') meetingsBarCmp: Child2Cmp;
...

child1Cmp.instance.loadingPnl.load(() => {....});
child2Cmp.loadingPnl.load(() => {....});

?

試試看:

import { Component, ViewChild } from '@angular/core';
import { Child1Component } from './child1/child1.component';
import { Child2Component } from './child2/child2.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child1Component) child1: Child1Component;
  @ViewChild(Child2Component) child2: Child2Component;

  ngAfterViewInit() {
    this.child1.child1Method();
    this.child2.child2Method();
  }

}

在您的模板中:

<child1></child1>

<child2></child2>

PS:您可以確保可以訪問ngAfterViewInit的子組件實例,因為那是當視圖完全加載時。


這是供您參考的工作樣本StackBlitz

您可以利用 ViewChild 在父組件中調用 child 2 的方法。 看看下面的內容。

家長:

import { Component, ViewChild } from '@angular/core';
import { Child1Component } from './child1/child1.component';

@Component({
  selector: 'my-app',
  templateUrl: '
        <div>
        <child1 #Child1Component></child1>
        </div>',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child1Component) child1?: Child1Component;

  customMethod() {
    this.child1?.child2?.someMethodOfChild2();

  }

孩子 1:

import { Component, ViewChild } from '@angular/core';
import { Child2Component } from './child2/child2.component';

@Component({
  selector: 'child1',
  templateUrl: '
        <div>
        <child2 #Child2Component></child2>
        </div>',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child2Component) child2?: Child2Component;

}

暫無
暫無

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

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