2016-08-16 5 views
17

私が呼び出したいメソッドを持っている子コンポーネントを作成しました。コール親クラスから子コンポーネント方法 - 角度

このメソッドを呼び出すと、console.log()行だけが起動されますが、testプロパティは設定されません。

以下は私の変化とクイックスタート角度アプリです。私もtestプロパティを設定するにはどうすればよい

import { Component } from '@angular/core'; 
import { NotifyComponent } from './notify.component'; 

@Component({ 
    selector: 'my-app', 
    template: 
    ` 
    <button (click)="submit()">Call Child Component Method</button> 
    ` 
}) 
export class AppComponent { 
    private notify: NotifyComponent; 

    constructor() { 
     this.notify = new NotifyComponent(); 
    } 

    submit(): void { 
     // execute child component method 
     notify.callMethod(); 
    } 
} 

子供

import { Component, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'notify', 
    template: '<h3>Notify {{test}}</h3>' 
}) 
export class NotifyComponent implements OnInit { 
    test:string; 
    constructor() { } 

    ngOnInit() { } 

    callMethod(): void { 
     console.log('successfully executed.'); 
     this.test = 'Me'; 
    } 
} 

答えて

32

あなたはこのlink

タイプセレクタで

@Component({ 
    selector: 'child-cmp', 
    template: '<p>child</p>' 
}) 
class ChildCmp { 
    doSomething() {} 
} 
@Component({ 
    selector: 'some-cmp', 
    template: '<child-cmp></child-cmp>', 
    directives: [ChildCmp] 
}) 
class SomeCmp { 
    @ViewChild(ChildCmp) child:ChildCmp; 
    ngAfterViewInit() { 
    // child is set 
    this.child.doSomething(); 
    } 
} 

文字列セレクタで

をチェック詳細は @ViewChildを使用してこれを行うことができます
@Component({ 
    selector: 'child-cmp', 
    template: '<p>child</p>' 
}) 
class ChildCmp { 
    doSomething() {} 
} 
@Component({ 
    selector: 'some-cmp', 
    template: '<child-cmp #child></child-cmp>', 
    directives: [ChildCmp] 
}) 
class SomeCmp { 
    @ViewChild('child') child:ChildCmp; 
    ngAfterViewInit() { 
    // child is set 
    this.child.doSomething(); 
    } 
} 
+2

を子コンポーネントのメソッドを呼び出しますあなたのアプローチですが、直接使用しているときにエラーが発生していますives:[ChildCmp]、エラーメッセージ:指示は 'タイプ'コンポーネント 'に存在しません。私はそれを見つけたし、rc5ではディレクティブが非難されています。だから新しいバージョンでそれを処理する方法。助けてください。 –

+0

このリンクhttps://angular.io/guide/component-interactionを試してみて、ディレクティブは、この行のChildVMは何 – rashfmnb

0

これは私のために働きました! 2角度のために、親コンポーネントで、私は続い

Parent.component.ts

import { Component, OnInit, ViewChild } from '@angular/core'; 
    import { ChildComponent } from '../child/child'; 
    @Component({ 
       selector: 'parent-app', 
       template: `<child-cmp></child-cmp>` 
       }) 
    export class parentComponent implements OnInit{ 
     @ViewChild(ChildComponent) child: ChildVM; 

     ngOnInit() { 
      this.child.ChildTestCmp(); } 
} 

Child.component.ts

import { Component} from '@angular/core'; @Component({ selector: 'child-cmp', template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> ` }) export class ChildComponent { test: string; ChildTestCmp() { this.test = "I am child component!"; } } 

+0

をリンクコメント:@ViewChild(ChildComponent)子:ChildVM。 –

関連する問題