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

Din*_*ino 2 methods parent-child angular

我试图使用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>
Run Code Online (Sandbox Code Playgroud)

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

import { SharedModule } from '../../shared'; //child declaration is inside here
Run Code Online (Sandbox Code Playgroud)

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

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);
    }}
}
Run Code Online (Sandbox Code Playgroud)

当我通过单击我的HTML中声明的方式调用getParts(value)时,我收到以下错误:

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

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

eko*_*eko 6

父html应该像:

<child-component #childComponent></child-component>
Run Code Online (Sandbox Code Playgroud)

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

export class ParentComponent implements OnChanges, OnInit {
    ...

    @ViewChild('childComponent') childComponent;
Run Code Online (Sandbox Code Playgroud)

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