首页 文章

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

提问于
浏览
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();
}

我得到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 . 我可以从子组件打开模态 - 这是工作,但是当我尝试从父组件执行时,我有问题 . 请提示!:)

此致,博斯珀

1 回答

  • 0

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

    @ViewChild(FormComponent)
        private formComponent: FormComponent;
    
        ngAfterViewInit() {
            this.formComponent.lgModal.show();
        }
    

相关问题