2017-07-13 4 views
1

私はStackOverflowで提案されている別のメソッドを使用しようとしましたが、以下の作業を行うことはできません。角2親から子コンポーネントメソッドを呼び出す

私はParentComponentに入れ子のChildComponentを持っています。

ここでは、親の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); 
    }} 
} 

私がHTで宣言されたをクリックしてgetParts(値)を呼び出すと、 ML以下のエラーが表示されます:

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

多くのユーザーが提案しているこのアプローチには何が問題なのですか?

答えて

4

親HTMLのようなする必要があります。

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

、あなたが今@ViewChild

export class ParentComponent implements OnChanges, OnInit { 
    ... 

    @ViewChild('childComponent') childComponent; 

と、この要素にアクセスすることができ、あなたのテンプレートに#ChildComponentセレクタを持っていないので、あなたの@ViewChild('ChildComponent') childComponent;は何も選択しません。

+0

親愛なるechonaxには、他に何かがあるはずです。私は、提案されたコードを修正して、同じエラーを与えています。 – Dino

+0

@Dinoはあなたの質問を編集した方法で更新できますか?大文字/小文字の単語には注意してください。 – echonax

+0

あなたは星のエコーナックスですが、それは確かに大文字/小文字の問題でした。私は数百万回のコードに行きました... – Dino

関連する問題