2016-09-14 22 views
1

私はng2 RC6で作業しています。私は親コンポーネントと子コンポーネントを持っています。子コンポーネント内Angular2 - 親コンポーネント内の子コンポーネントから関数を実行

私はNG2-ブートストラップモーダルを得て、機能を開始:親コンポーネントで

import { Component, ViewChild, AfterViewInit, Input } from '@angular/core'; 
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap'; 

@Component({ 
    selector: 'nba-form', 
    templateUrl: './form.component.html' 
}) 


export class FormComponent { 
    public modal:boolean = false; 

    @ViewChild('childModal') public childModal: ModalDirective; 
    @ViewChild('lgModal') public lgModal: ModalDirective; 

    public showChildModal(): void { 
     this.childModal.show(); 
    } 

    public hideChildModal(): void { 
     this.childModal.hide(); 
    } 

    ngAfterViewInit() { 
     this.lgModal.show(); 
    } 
} 

私は機能を実行するモーダルウィンドウを開いている「this.lgModal.show()」、。

{...} 
import { FormComponent } from './form.component'; 
import 'rxjs/add/operator/toPromise'; 

@Component({ 
    selector: 'nba', 
    templateUrl: './nba.component.html', 
    providers: [FormComponent] 
}) 
export class NbaComponent implements OnInit { 

    constructor(private appService: AppService, private formComponent: FormComponent) {} 

しかしI'amは使用して:

import { NgModule }  from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { FormsModule } from '@angular/forms'; 
import { HttpModule, JsonpModule } from '@angular/http'; 

import { ModalModule } from 'ng2-bootstrap/ng2-bootstrap'; 
import { AlertModule, DatepickerModule } from 'ng2-bootstrap/ng2-bootstrap'; 

// Imports for loading & configuring the in-memory web api 
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api'; 
import { InMemoryData } from './in-memory-data'; 

import { FormComponent } from './form.component'; 
import { NbaComponent } from './nba.component'; 
import { AppComponent } from './app.component'; 
import { AppService } from './app.service'; 
import { routing } from './app.routing'; 

@NgModule({ 
    imports: [ 
    BrowserModule, 
    AlertModule, 
    FormsModule, 
    HttpModule, 
    DatepickerModule, 
    InMemoryWebApiModule.forRoot(InMemoryData), 
    ModalModule, 
    routing 
    ], 
    declarations: [AppComponent, NbaComponent, FormComponent], 
    providers: [AppService], 
    bootstrap: [AppComponent] 
}) 

export class AppModule { 

} 

PS:

ngOnInit() { 
    this.formComponent.lgModal.show(); 
} 

私はshow();が未定義

そしてapp.module.tsであることERRを得ました。私は子コンポーネントからモーダルを開くことができます - これは仕事ですが、親コンポーネントからしようとすると問題があります。 !ヒントのためしてください:)

よろしく、私は子関数の実行wannt注釈@ViewChild()、と親に子コンポーネントのインスタンスを追加することで解決 Bosper

+0

あなたは 'でそれを試みることができますngAfterViewInit'? – rinukkusu

+0

私は試みましたが、結果は同じです: "未定義のプロパティ 'show'を読むことができません:( –

+0

なぜ' formComponent'プロバイダですか?コンポーネントでありインスタンス化されていない場合、 – rinukkusu

答えて

0

は:

@ViewChild(FormComponent) 
    private formComponent: FormComponent; 

    ngAfterViewInit() { 
     this.formComponent.lgModal.show(); 
    } 
関連する問題