简体   繁体   中英

Angular pass component as method parameter (ngComponentOutlet) issue

I am loading some components at runtime like this:

load(): any {
  this.comp = OneComponent;
}

And calling it like this:

<ng-container *ngComponentOutlet="comp"></ng-container>
<button (click)="load()">Load Component One</button>

The above works but I want to use the same method to call multiple components...so I want to do something like this:

loadComponent(comp): any {
  this.comp = comp;
}

But when I try calling it like this:

<button (click)="load('OneComponent')">Load Component</button> <!-- This doesn't work -->

The above I cannot do... I know it's a string but I cannot add:

(click)="load(OneComponent)" either.

So, how do I do this?

You'd need to provide the actual component as the parameter to *ngComponentOutlet . At the moment you're sending only the string 'OneComponent' .

Try the following

Controller (*.ts)

compMapping = {
  "one": OneComponent,
  "two": TwoComponent,
  ...
};

loadComponent(comp): any {
  if (!!this.compMapping[comp]) {
    this.comp = this.compMapping[comp];
  }
}

Template (*.html)

<button (click)="load('one')">Load Component</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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