Angular2 - Insert an active instance of AppComponent into a child component

My child components of the application must access the active instance of AppComponent for various reasons, so I tried below to get a link to the AppComponent in ChildComponents, but it does not insert the active instance of AppComponent, but receives a new instance of AppComponent in all of my child components. So how to solve this problem.

Submitted Source in GIT

https://github.com/jeevaengg21/angular2-parent-inject

Update

import { NgModule, Inject, forwardRef } from '@angular/core';

@Component({
  selector: 'child-page1',
  templateUrl: './child.component.html',
})
export class ChildComponent1 implements IChild {
...
constructor(private appComponent: AppComponent) {
  console.log('inside ChildComponent1'+appComponent);

}
...
}

child.lazy.module.ts

import { NgModule, forwardRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildComponent } from './child.component';
import { ChildRoutingModule } from './child.lazy.routing';
import { AppComponent } from '../app.component';
import { AppModule } from '../app.module';
import { Routes, RouterModule } from '@angular/router';

@NgModule({
  imports: [CommonModule,ChildRoutingModule],
  declarations: [ChildComponent]
})
export class ChildModule {}

child.lazy.routing.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ChildComponent } from './child.component';

const appRoutes: Routes = [
    { path: '', component: ChildComponent },
];

@NgModule({
    imports: [
        RouterModule.forChild(appRoutes)
    ],
    exports: [
        RouterModule
    ]
})
export class ChildRoutingModule { }

app.routing.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
    { path: '', redirectTo: '/child', pathMatch: 'full' },
    { path: 'child', loadChildren: "app/child/child.lazy.module#ChildModule" },
 ];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule { }

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, AppRoutingModule,
    FormsModule,
    HttpModule,
    ReactiveFormsModule,

  ],
  providers: [MainService],
  bootstrap: [AppComponent]
})
export class AppModule {}

It is decided:

Update Angular2 and Angular-cli

+4
source share

Source: https://habr.com/ru/post/1668786/


All Articles