首页 文章

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

提问于
浏览
2

我试图使用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 EXCEPTION:无法读取未定义的属性'openDialog'

许多用户提出的这种方法有什么问题?

1 回答

  • 6

    父html应该像:

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

    然后你可以用 @ViewChild 访问这个元素

    export class ParentComponent implements OnChanges, OnInit {
        ...
    
        @ViewChild('childComponent') childComponent;
    

    现在你的 @ViewChild('ChildComponent') childComponent; 没有选择,因为你的模板中没有 #ChildComponent 选择器 .

相关问题