jonyeezs
jonyeezs

Reputation: 41

How to get a component/element provider injector within its node definition

tl;dr: During debug/development how can I can view a particular html element's provider injector or better yet its node definition.

So according to this blog post

Each view node is created using a node definition that holds metadata describing the node.

In Angular, a node definition that describes an HTML element defines its own injector. In other words, an HTML element in a component’s template defines its own element injector. And this injector can populated with providers by applying one or more directives on the corresponding HTML element.

The definition that Angular creates for this template includes the following metadata for the div element [See gist]

How can i see my element's node definition in my app during debugging? ie in my Chrome dev tools.

Upvotes: 1

Views: 1154

Answers (2)

Max Koretskyi
Max Koretskyi

Reputation: 105517

Suppose you have the following directive that adds a provider:

@Directive({
    selector: '[provider]',
    providers: [
        {
            provide: 'token',
            useValue: 'value'
        }
    ]
})
export class ProviderDirective {
    constructor() {
        console.log('Ptovider Dir');
    }
}

And use it in a template like this:

@Component({
    selector: 'a-comp',
    template: `
        <div provider>I am div with a provider</div>
    `
})
export class AComponent {}

To find the element definition and providers added by the directive, open a console, select the div element and type the following:

ng.probe($0).injector.elDef

There you'll see element property pointing to an object with public providers.

Upvotes: 2

user4676340
user4676340

Reputation:

In Chrome dev-tools, during ng serve :

  • inspect an element of the component you want to watch
  • it will be highlighted in the dev tools Elements tab
  • find the parent tag (usually app-something)
  • click on it

Now, if you input console.log($0) in your console, it should display this element. Don't select another element, as you would loose the context of this component.

  • input const comp = ng.probe($0).componentInstance

You now have a reference to your component.

I'm not sure you can have access to its injector unless you declare it as a dependency though.

Upvotes: 1

Related Questions