4

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 element in the DOM will have an attribute name of something like _nghost-par-2. Which, is a unique ID given to the component to encapsulate the associated styles.

How do you get that ID as part of the component's constructor?

Something to the effect of:

@Component({
  hostId:string;
  ...
})
export class myComponent implements OnInit {
  constructor(host:Host) {
    this.hostId = host.id;
  }
  ...
}
VladoDemcak
  • 4,893
  • 4
  • 35
  • 42
Brenton
  • 317
  • 2
  • 9

1 Answers1

4

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • First time I'm see a string being build that way. That's different. Also, if anyone else is looking at this, don't forget to add APP_ID, and Inject to your @angular/core import. – Brenton Nov 01 '16 at 18:31
  • One more thing, '_nghost' is the static portion of the root component. '_ngcontent' is for each sub component. Read more here: http://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html – Brenton Nov 01 '16 at 18:40