我尝试使用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不会选择任何内容。

08-03 21:37