问题
I have many components with different selectors like app-protocol, app-inspection, app-generalview etc. I want the rendered component to be based on a variable, something like:
In Typescript
view = 'protocol'; // or inspection or generalview
In HTML
<app-{{view}}> </app-{{view}}>
or
<div [innerHTML] = "'<app-{{view}}>'"> </div>
Both HTML examples however don't work. I know I can use an *ngSwitch but I could have many cases and would like to know if there is a way to avoid doing that. Thanks a lot.
回答1:
You can rended dinamically the component using componentFactoryResolver
and viewContainerRef
.
Here's a simple example, I've created the component called Cmp1Component
that is going to be renderd dinamically.
App.module.ts
@NgModule({
declarations: [
AppComponent,
Cmp1Component,
Cmp2Component
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent],
entryComponents:[
Cmp1Component
]
})
export class AppModule { }
App.component.html
A component will be rendered down here:
<div #placeholder></div>
App.component.ts
import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { Cmp1Component } from './cmp1/cmp1.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public done = false;
@ViewChild("placeholder", {read: ViewContainerRef}) placeholderRef: ViewContainerRef;
constructor(
public viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) {
}
ngAfterViewChecked(): void {
if(!!this.placeholderRef && !this.done){
this.done = true;
const factory = this.componentFactoryResolver.resolveComponentFactory(Cmp1Component);
const componentRef = this.placeholderRef.createComponent(factory);
componentRef.changeDetectorRef.detectChanges();
}
}
}
Result:
One thing : you may not need to put the logic into the ngAfterViewChecked
cycle. I've done this logic just to show you how it works. If you actually put the code in a function that will be executed when everything is rendered, then you know for sure that placeHolderRef
is not null or undefined.
来源:https://stackoverflow.com/questions/53226385/string-interpolation-for-angular-html-selector