Can you get the component encapsulation host ID?

前端 未结 1 1446
半阙折子戏
半阙折子戏 2021-01-15 05:53

Is there a way to get the encapsulation host id that is given to a component?

If you have a component that is using ViewEncapsulation.Emulated the eleme

1条回答
  •  深忆病人
    2021-01-15 06:15

    This ID consists of the following parts:

    _nghost   -   par    -     2
       |           |           |
     static      APP_ID   _nextCompTypeId
    

    APP_ID is a just token from @angular/core

    If you need to avoid randomly generated value to be used as an application id, you can provide a custom value via a DI provider configuring the root Injector using this token

    _nextCompTypeId is generated inside framework within private class ViewUtils.

    Seems there is no a public method which can return it value. So probably the following will work

    export class MyComponent { 
      id: string;
      constructor(@Inject(APP_ID) appId: string, vcRef: ViewContainerRef) {
        this.id = `${appId}-${vcRef.injector['_view'].viewUtils._nextCompTypeId - 1}`;
      }
    }
    

    Another way is get it from attributes via elementRef

    Update

    If you're on Angular 9 then follow this answer How to access components unique encapsulation ID in Angular 9

    0 讨论(0)
提交回复
热议问题