1

我正在研究 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。我可以从子组件打开模式 - 这是可行的,但是当我尝试从父组件打开时,我遇到了问题。请指教!:)

问候, 博斯珀

4

1 回答 1

0

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

@ViewChild(FormComponent)
    private formComponent: FormComponent;

    ngAfterViewInit() {
        this.formComponent.lgModal.show();
    }
于 2016-09-15T07:41:44.597 回答