Angular: How to get component instance of router-outlet

18,548

Don't try to use RouterOutlet as a provider. Instead add the (activate) attribute to your router-outlet tag like this:

<router-outlet (activate)="onRouterOutletActivate($event)"></router-outlet>

And then in the component containing the router-outlet element (your AppComponent class) you should implement the onRouterOutletActivate method:

public onRouterOutletActivate(event : any) {
    console.log(event);
}

which will give you the route component instance in the event parameter, in this example written to the web console.

Share:
18,548

Related videos on Youtube

Dharan Ganesan
Author by

Dharan Ganesan

Develop, document, and unit-test new product features and bug fixes while ensuring compatibility in all supported browsers Provide coaching, mentoring, and leadership to junior and intermediate team members Review peer-written code and provide constructive feedback Responsible for coding the execution of complex designs and interactions that reflect the creative and art direction provided within the established technical framework.

Updated on June 11, 2022

Comments

  • Dharan Ganesan
    Dharan Ganesan almost 2 years

    html:

    <router-outlet></router-outlet>
    

    component:

    @Component({
          selector: 'xx',
          templateUrl: './xx.html',
          styleUrls: ['./xx.css'],
          providers: [ RouterOutlet]
        })
        export class AppComponent {
        constructor(private routeroutlet: RouterOutlet){ }
        getref() {
         console.log(this.routeroutlet);
         console.log('refresh', this.routeroutlet.component);
        }
    }
    

    i'm getting this error

    core.es5.js:1224 ERROR Error: Outlet is not activated
        at RouterOutlet.get [as component] (router.es5.js:5449)
        at AppComponent.onRefreshscrum (app.component.ts:343)
        at Object.eval [as handleEvent] (AppComponent.ngfactory.js:111)
        at Object.handleEvent (core.es5.js:12251)
        at Object.handleEvent (core.es5.js:12975)
        at dispatchEvent (core.es5.js:8863)
        at eval (core.es5.js:11025)
        at SafeSubscriber.schedulerFn [as _next] (core.es5.js:3851)
        at SafeSubscriber.__tryOrUnsub (Subscriber.js:223)
        at SafeSubscriber.next (Subscriber.js:172)
    

    console result:(this.routeroutlet)

    RouterOutlet {
    parentContexts: ChildrenOutletContexts, 
    location: null, 
    resolver: CodegenComponentFactoryResolver, 
    changeDetector: ViewRef_, 
    activated: null, …}activateEvents: EventEmitter {_isScalar: false, observers: Array(0), 
    closed: false, 
    isStopped: false, 
    hasError: false, 
    …}
    closed: false
    hasError: false
    isStopped: false
    observers: []thrown
    Error: null
    __isAsync: false
    _isScalar: false
    __proto__: Subject
    activated: null
    activatedRoute: (...)activatedRouteData: (...)changeDetector: ViewRef_ {_view: {…}, _viewContainerRef: null, _appRef: null}
    component: [Exception: Error: Outlet is not activated
        at RouterOutlet.get [as component] (webpack:///./~/@angular/router/@angular/router.es5.js?:5449:23)
        at RouterOutlet.remoteFunction (<anonymous>:2:26)]deactivateEvents: EventEmitter {_isScalar: false, observers: Array(0), 
    closed: false, 
    isStopped: false, 
    hasError: false, …}
    isActivated: (...)location: nulllocationFactoryResolver: (...)l
    ocationInjector: (...)name: "primary"
    parentContexts: ChildrenOutletContexts {contexts: Map(1)}resolver: CodegenComponentFactoryResolver {_parent: null, _ngModule: NgModuleRef_, _factories: Map(52)}_activatedRoute: null__proto__: ObjectactivateWith: ƒ (activatedRoute, resolver)activatedRoute: (...)activatedRouteData: (...)attach: ƒ (ref, activatedRoute)component: (...)deactivate: ƒ ()detach: ƒ ()isActivated: (...)locationFactoryResolver: (...)locationInjector: (...)ngOnDestroy: ƒ ()ngOnInit: ƒ ()arguments: (...)caller: (...)length: 0name: ""prototype: {constructor: ƒ}__proto__: ƒ ()[[FunctionLocation]]: router.es5.js:5400[[Scopes]]: Scopes[3]constructor: ƒ RouterOutlet(parentContexts, location, resolver, name, changeDetector)get activatedRoute: ƒ ()get activatedRouteData: ƒ ()get component: ƒ ()get isActivated: ƒ ()get locationFactoryResolver: ƒ ()get locationInjector: ƒ ()__proto__: Object
    

    The above console result is for console the routeroutlet obj.

    I want to access the instance of the component which is rendered in router-outlet. how i access the instance of the component?

  • Peter Salomonsen
    Peter Salomonsen almost 7 years
    See app.component.ts in this plunk: plnkr.co/edit/v6YxXhAq8yHs2QT0rEFX?p=preview Open the webconsole to see the component instance written to the console log
  • Dharan Ganesan
    Dharan Ganesan almost 7 years
    thnks bro..! it's running
  • alex351
    alex351 over 5 years
    your plnkr is dead.
  • Kumaresan Sd
    Kumaresan Sd over 4 years
    but while initial loading, child component wont get displayed in DOM....sample - stackblitz.com/edit/…
  • aruno
    aruno over 4 years
    Looks like nobody liked this - but wanted to add that this no longer works with ivy since the newly added component element is now after the existing one (so nextSibling gives you the existing component about to be replaced).
  • Captain Prinny
    Captain Prinny almost 4 years
    Not finding that this works in Angular 8. event is undefined