【问题标题】:Angular 6: Access to child of child component (from parent one)Angular 6:访问子组件的子组件(从父组件)
【发布时间】:2021-12-02 22:44:23
【问题描述】:

如何访问(调用某些方法)某个父(容器)组件的(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(() => {....});

?

【问题讨论】:

标签: angular typescript dependency-injection angular6 angular7


【解决方案1】:

试试这个:

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 中的子组件实例,因为此时视图将被完全加载。


这里有一个Working Sample StackBlitz 供您参考。

【讨论】:

  • 嗯,不是真的......需要访问孩子的孩子(!)(不是直接孩子 - 那个很明显);子(子)是一种动态组件(加载器组件将观察者函数作为参数(@Input)并在它完成后 - 发出(让知道它是父组件(“第一个”子 - child1)
  • 我认为用这个细节来更新你的问题是个好主意。您的问题并不直接暗示需要孩子的孩子访问权限。
【解决方案2】:

您可以利用 ViewChild 在父组件中调用子 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;

}

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2019-10-10
    • 2020-07-10
    • 2020-04-14
    相关资源
    最近更新 更多