Angular 2 calling a child component method from the parent

吃可爱长大的小学妹 提交于 2019-12-22 12:37:15

问题


I have tried to use different methods suggested in StackOverflow but I cannot make the following work.

I have a nested ChildComponent into a ParentComponent.

Here the HTML of the parent:

<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>

Obviously, I have imported the child component into the parent one:

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

in the parent component, I am implementing the following code:

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);
    }}
}

When I call the getParts(value) by clicking on the declared in my HTML I get the following error:

VM21157:55 EXCEPTION: Cannot read property 'openDialog' of undefined

what is wrong with this approach suggested by many users?


回答1:


Parent html should be like:

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

then you can access this element with @ViewChild

export class ParentComponent implements OnChanges, OnInit {
    ...

    @ViewChild('childComponent') childComponent;

Right now your @ViewChild('ChildComponent') childComponent; selects nothing since you don't have a #ChildComponent selector in your template.



来源:https://stackoverflow.com/questions/45078725/angular-2-calling-a-child-component-method-from-the-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!