How to check if a component exists in Angular 1.5

和自甴很熟 提交于 2020-01-13 19:20:14

问题


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.



来源:https://stackoverflow.com/questions/39992146/how-to-check-if-a-component-exists-in-angular-1-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!