首页 > 解决方案 > 模板中的角度变量选择器

问题描述

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

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

我可能可以使用这样的 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>

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

<{{template}}></{{template}}>

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

标签: angularangular-template

解决方案


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

   <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
       
            }
        }


      }
    }

推荐阅读