简体   繁体   English

基于属性选择器动态创建组件

[英]Create components dynamically based on attribute selector

Context语境

In my application, admins can freely configure some forms that needs to be compiled by other users.在我的应用中,管理员可以自由配置一些需要其他用户编译的forms。 Those forms can have an arbitrary number of inputs of predefined types (like integers, checkboxes, text and so on...)那些 forms 可以有任意数量的预定义类型的输入(如整数、复选框、文本等......)

This configuration comes from the server in this way (exemplified):此配置以这种方式来自服务器(示例):

{ fields: [
   { type: "typeA", maxValue: 50, ...},
   { type: "typeB", maxValue: 70, ...},
   { type: "typeC", maxValue: 40, ...},
   ...
]}

To handle this, i built a number of input components with an attribute selector:为了处理这个问题,我构建了一些带有属性选择器的输入组件:

@Component({
  selector: 'component[type=typeA]',
  template: `
    <mat-form-field class="w100p" [floatLabel]="label != null ? 'auto' : 'never'">
    ....
`

The Problem问题

How can i build a component via attribute selector specified in a variable ?如何通过变量中指定的属性选择器构建组件? I already tried with:我已经尝试过:

<div> 
  <component type="typeInVariable"></component> 
</div>

where typeInVariable has value typeB , but angular returns me an error: Template parse errors: 'component' is not a known element:其中typeInVariable的值为typeB ,但 angular 返回一个错误: Template parse errors: 'component' is not a known element:

How can i solve this?我该如何解决这个问题? I also have created a stackblitz sample here .我还在这里创建了一个 stackblitz 示例。

Perhaps you should use dynamic components here.也许您应该在这里使用动态组件。

Some references:一些参考资料:

https://angular.io/guide/dynamic-component-loader https://angular.io/guide/dynamic-component-loader

https://netbasal.com/things-worth-knowing-about-dynamic-components-in-angular-166ce136b3eb https://netbasal.com/things-worth-knowing-about-dynamic-components-in-angular-166ce136b3eb

I have had a similar requirement and it worked for me.我有类似的要求,它对我有用。 Let me know if you need any more explanation.如果您需要更多解释,请告诉我。

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

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