如何从app组件调用其他模块组件功能

时间:2017-11-03 07:06:38

标签: angular

我的应用程序有app模块和仪表板模块,仪表板模块有很多组件。我必须从app组件触发仪表板组件功能(changedivStatus)。

我希望通过使用发送和订阅的EventEmitter服务来实现这一点。

没有服务还有其他办法。

  

app.module.ts

import { NgModule }                     from '@angular/core';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
import { BrowserModule }                from '@angular/platform-browser';
import {BrowserAnimationsModule,NoopAnimationsModule}       from '@angular/platform-browser/animations';
import { DashboardModule }              from './dashboard/dashboard.module';
  

dashboard.module.ts

import { NgModule }               from '@angular/core';
import { BrowserModule }          from '@angular/platform-browser';
import { RouterModule }         from '@angular/router';
import { WidgetsModule }          from '../widgets/widgets.module';
import { SharedModule }          from '../shared/shared.module';
import { DashboardComponent }     from './dashboard/dashboard.component';
import { AppSelectorComponent }   from './app-selector/app-selector.component';
import { AppReportsComponent }   from './app-reports/app-reports.component';
import {AppReportsService} from '../shared/services/app-reports.service';
import { BsDropdownModule }   from 'ngx-bootstrap/dropdown';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatSidenavModule,MatDatepickerModule} from '@angular/material';
import {CheckboxModule} from 'primeng/primeng';
import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [
        BrowserModule,
        SharedModule,
        WidgetsModule,
        BsDropdownModule,
        RouterModule,
        FormsModule,
        CheckboxModule,
        BrowserAnimationsModule,
        MatSidenavModule,
        MatDatepickerModule
    ],
    declarations: [
        DashboardComponent,
        AppSelectorComponent,
        AppReportsComponent
    ],
    providers: [
        AppReportsService
    ],
    exports: [
        DashboardComponent
    ]
})

export class DashboardModule {

}
  

app.component.html

<div class="reports_container fRight" *ngIf="!firstVisit">
    <input type="checkbox" (click)="changedivStatus()" class="md-primary" [checked]="showReport" />
    <span style="font-size: 12px">Hide Banner</span>
</div>
  

dashborad.component.html

<div class="row">
<div class="col-md-12 col-sm-12 col-lg-12">
    <app-app-reports [items]="apps" *ngIf="loadReport"></app-app-reports>
</div>
</div>
  

dashboard.component.ts

changedivStatus() {
        this.showReport = !this.showReport;
        if(!this.showReport) {
            this.loadReport = true;
        } else {
            this.loadReport = false;
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用服务,将changeDivStatus()功能放在dashboard.service中,从app.component触发,从dashboard.service发出事件并订阅此服务。您的dashboard.component ngOnInit函数中的事件。

以下是服务的官方角度指南:https://angular.io/tutorial/toh-pt4