繁体   English   中英

Angular 2从父级调用子级组件方法

[英]Angular 2 calling a child component method from the parent

我尝试使用StackOverflow中建议的其他方法,但无法进行以下工作。

我有一个嵌套的ChildComponent到ParentComponent中。

这里是父级的HTML:

<div> ... <div>

<span *ngIf="value" class="option-button cursor-pointer" [attr.modelURL]="value"
      (click)="$event.stopPropagation();getParts(assemblyLibrary)">
    <i class="fa fa-cube"></i>
</span>

<child-component></child-component>

显然,我已经将子组件导入了父组件:

import { SharedModule } from '../../shared'; //child declaration is inside here

在父组件中,我正在实现以下代码:

import { child-component } from '../../../child-component';

@Component({
    selector: 'parent-component',
    templateUrl: './parent-component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ParentComponent implements OnChanges, OnInit {
    ...

    @ViewChild('ChildComponent') childComponent;

    openDialog(filesToLoad) {
        this.childComponent.openDialog(filesToLoad);
    }

    getParts(value) {
        this.filesToLoad = [];

        ... code to populate files to load

        this.openDialog(this.filesToLoad);
    }}
}

当我通过单击HTML中声明的来调用getParts(value)时,出现以下错误:

VM21157:55例外:无法读取未定义的属性'openDialog'

许多用户建议的这种方法有什么问题?

父html应该像这样:

<child-component #childComponent></child-component>

那么您可以使用@ViewChild访问此元素

export class ParentComponent implements OnChanges, OnInit {
    ...

    @ViewChild('childComponent') childComponent;

现在,您的@ViewChild('ChildComponent') childComponent; 由于您的模板中没有#ChildComponent选择器,因此不会选择任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM