-2

I feel like what I want to do should be dead simple but here we are...

Basically I want to use one of many possible selectors to add one of many components.

I could probably use a ng-switch like this

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

But common there HAS to be a way to do something like this:

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

So I just need to pass in the string 'comp-2' as "template" and it will generate a component.

Doopdon
  • 125
  • 2
  • 10
  • This may be what you are looking for: https://stackoverflow.com/a/49667171/6559330. But I think it is much cleaner and easier to read having them listed out and using ngIf to hide / show them. – Brian Smith Jun 24 '21 at 19:53
  • it wont be cleaner when the switch case is 50+ rows long. – Doopdon Jun 24 '21 at 20:12

1 Answers1

0

I recommend using the dynamic component generation technique , so create a component like this :

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


      }
    }
  • I would like the "generate component" code filled in. As I have no idea how to generate an component, also I am trying to NOT use a switch case. I have one of at least 12 components it could be, and more are on the way. – Doopdon Jun 24 '21 at 20:11