Retrieving the active component and path

前端 未结 5 559
既然无缘
既然无缘 2021-01-12 22:51

With Angular2, how would I retrieve the current active component and path?

For example I might have the following routes:

{ path: \'\', component:          


        
5条回答
  •  余生分开走
    2021-01-12 23:36

    In ActivatedRouteSnapshot the component property is defined as being one of the following

    component: Type | string | null;
    

    So you can't just do component.name unless you've already made sure you have Type. This is because .name on a string doesn't exist.

    Now Type is actually a function that creates the type (your component type) and is defined as:

    export interface Type extends Function {
        new (...args: any[]): T;
    }
    

    So you can do something like this, which will actually compile

     if (typeof(this.route.snapshot.component) === 'function')
     {
         // the compiler is 'smart' enough to know that component here must be Type
         const name = this.route.snapshot.component.name;
     }
    

    An 'elegant' way to do it is using a typescript typeguard (although to be frank in this case it doesn't give you much of a benefit over what I just said).

    isComponent(item: Type | string | null): item is Type
    {
        return typeof item === 'function';
    }
    

    Then you can say this.name = isComponent(this.route.snapshot.component) ? this.route.snapshot.component : null.

    Important: component.name is still valid in an AOT build, but unfortunately with --prod it will end up being something random like r.

    I've resorted to having to inject private element: ElementRef and then look for the tag name. This will still be present even with an AOT prod build. There may be a performance cost to doing this so cache it if you're using it a lot.

        if (element.nativeElement.tagName.startsWith('RR-')){
            super.name = element.nativeElement.tagName;
        }
    

提交回复
热议问题