Dino
Dino

Reputation: 1347

Angular 2 calling a child component method from the parent

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?

Upvotes: 2

Views: 4179

Answers (1)

eko
eko

Reputation: 40647

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.

Upvotes: 6

Related Questions