How to check if a component exists in Angular 1.5

2019-05-18 19:21发布

问题:

http://embed.plnkr.co/oGlcQSOM2vFcDEKP7thV/

$injector.has('myMessageDirective') returns true, while $injector.has('myMessageComponent') does not

Is anyone struggling with this or has a solution? My "fear" is that my components might not be found in future updates because of the directive check.

Follow up question to: Check if an Angular directive exists

回答1:

At the end of the day, a component is registered as a directive, so 'Directive' suffix is indeed needed.

Check 'has' method of $injector object:

return {
  invoke: invoke,
  instantiate: instantiate,
  get: getService,
  annotate: createInjector.$$annotate,
  has: function(name) {
    return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  }
};

You can debug it and see that all components (inside cache object) are registered as directives. There is no 'Component' suffix.



回答2:

I think, simplest way is to add an id attribute to directive's/component's container, then check if element with this id exist.