【问题标题】:Angular varable selector in Template模板中的角度变量选择器
【发布时间】:2021-06-24 19:41:53
【问题描述】:

我觉得我想做的事情应该很简单,但我们在这里......

基本上我想使用许多可能的选择器之一来添加许多组件之一。

我可能会使用这样的 ng-switch

<div ng-switch="template">
  <div ng-switch-when="comp-1">
    <comp-1></comp-1>
  </div>
   <div ng-switch-when="comp-2">
    <comp-2></comp-2>
  </div>
   <div ng-switch-when="comp-3">
    <comp-3></comp-3>
  </div>
  <div ng-switch-default>
    <h1>Hey now you need to go here ad add your comp which is annoying!</h1>
  </div>
</div>

但通常必须有一种方法来做这样的事情:

&lt;{{template}}&gt;&lt;/{{template}}&gt;

所以我只需要将字符串“comp-2”作为“模板”传入,它就会生成一个组件。

【问题讨论】:

  • 这可能是您正在寻找的:stackoverflow.com/a/49667171/6559330。但我认为将它们列出并使用 ngIf 隐藏/显示它们会更清晰、更容易阅读。
  • 当开关盒超过 50 行时,它不会更干净。

标签: angular angular-template


【解决方案1】:

我推荐使用动态组件生成技术,所以创建一个这样的组件:

   <app-custom [componentname]='comp-3'></app-custom>

   export class CustomComponent implements OnInit {
      @Input() componentname: any;
      @ViewChild('myVar') myVar:ElementRef;
      constructor() { }
      ngOnInit() {
        switch(this.componentname)
        {
            case "comp-3": 
            {
               this.myVar = //Generate component
       
            }
        }


      }
    }

【讨论】:

  • 我想填写“生成组件”代码。由于我不知道如何生成组件,所以我也试图不使用开关盒。我拥有至少 12 个组件中的一个,并且正在开发中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2015-01-25
  • 2020-09-10
  • 2020-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
相关资源
最近更新 更多