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

时间:2016-09-14 13:48:12

标签: angular typescript ng2-bootstrap

我正在研究ng2 RC6。我有父组件和子组件。

在子组件内部,我得到了ng2-bootstrap模态,并启动了函数:

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();
}

我得到show();未定义的ERR

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

1 个答案:

答案 0 :(得分:0)

通过在注释为@ViewChild()的父级中添加子组件的实例来解决,我想运行子函数:

@ViewChild(FormComponent)
    private formComponent: FormComponent;

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