简体   繁体   English

有没有更好的方法来访问 Angular 的组件私有属性?

[英]Is there a better way to access Angular's components private properties?

If you pass a component reference into a function you can access Component's properties through a private property called ɵcmp, for example:如果您将组件引用传递给 function,您可以通过名为 ɵcmp 的私有属性访问组件的属性,例如:

myFunction(TestComponent);

export function myFunction (component) {
  console.log('this is the component selector', component.ɵcmp.selectors[0]);
  console.log('these are component inputs', component.ɵcmp.inputs)
}

Is there any better way to access those properties without accessing this "magic" private property?有没有更好的方法来访问这些属性而不访问这个“神奇”的私有财产?

In v12 and below you could inject and then use ComponentFactoryResolver ( docs ) to get the components ComponentFactory ( docs ) which gives public access to those properties:在 v12 及以下版本中,您可以注入然后使用ComponentFactoryResolver ( docs ) 来获取组件ComponentFactory ( docs ),它可以让公众访问这些属性:

const factory: ComponentFactory = componentFactoryResolver.resolveComponentFactory(TestComponent);
console.log(factory.selector);
console.log(factory.inputs);
console.log(factory.outputs);

Although this method is now marked as deprecated in v13.尽管此方法现在在 v13 中被标记为已弃用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM