首页 > 解决方案 > View child/ 从父组件查看子组件到子组件

问题描述

我想 ViewChild 从父组件到子组件。

class ParentComponent {
  @ViewChild('CommentSection') commentBox: ElementRef
}

class ChildComponent {}

child.component.html

<textarea #CommentSection>
 </textarea>

可能吗?

我在 afterviewInit 函数中得到“未定义”

标签: angularangular5angular6

解决方案


您可以像这样访问子组件

import { Component, ViewChildren, AfterViewInit, QueryList } from '@angular/core';
import { MyComponent } from './mycomponent.component';

export class ParentComponent implements AfterViewInit
{

    @ViewChildren(MyComponent) childrenComponent: QueryList<MyComponent>;

    public ngAfterViewInit(): void
    {
        this.childrenComponent.changes.subscribe((comps: QueryList<MyComponent>) =>
        {
            // Now you can access the child component
        });
    }
}

推荐阅读