Angular2 - 从父组件中的子组件运行函数

Angular2 - 从父组件中的子组件运行函数

问题描述:

我正在使用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

由父母与注释@ViewChild(),在那里我wannt运行子功能附加子组件的情况下解决:

@ViewChild(FormComponent) 
    private formComponent: FormComponent; 

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