2016-09-14 69 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) {} 

但是當我'使用:

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

我ERR是show();是不確定

而且app.module.ts:

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。我可以從子組件打開模式 - 這是工作,但是當我嘗試從父組件執行時,我遇到了問題。 !請爲提示:)

問候, Bosper

+0

你能嘗試在' ngAfterViewInit'? – rinukkusu

+0

我曾嘗試過,結果是一樣的:「無法讀取未定義的屬性'顯示':( –

+0

爲什麼formComponent是一個提供者?它不應該在'directives'數組中,如果它是一個組件並且不被實例化通過構造函數中的DI? – rinukkusu

回答

0

由父母與註釋@ViewChild(),在那裏我wannt運行子功能附加子組件的情況下解決:

@ViewChild(FormComponent) 
    private formComponent: FormComponent; 

    ngAfterViewInit() { 
     this.formComponent.lgModal.show(); 
    } 
相關問題