角度HTML选择器的字符串插值 [英] String interpolation for angular HTML selector
问题描述
我有许多具有不同选择器的组件,例如app-protocol,app-inspection,app-generalview等.我希望呈现的组件基于变量,例如:
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:
在打字稿中
view = 'protocol'; // or inspection or generalview
在HTML中
<app-{{view}}> </app-{{view}}>
或
<div [innerHTML] = "'<app-{{view}}>'"> </div>
但是,这两个HTML示例都不起作用.我知道我可以使用* ngSwitch,但是我可能有很多情况,并且想知道是否有避免这种情况的方法.非常感谢.
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.
推荐答案
您可以使用componentFactoryResolver
和viewContainerRef
来动态查找组件.
You can rended dinamically the component using componentFactoryResolver
and viewContainerRef
.
这是一个简单的示例,我创建了名为Cmp1Component
的组件,该组件将进行动态渲染.
Here's a simple example, I've created the component called Cmp1Component
that is going to be renderd dinamically.
App.module.ts
App.module.ts
@NgModule({
declarations: [
AppComponent,
Cmp1Component,
Cmp2Component
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent],
entryComponents:[
Cmp1Component
]
})
export class AppModule { }
App.component.html
App.component.html
A component will be rendered down here:
<div #placeholder></div>
App.component.ts
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();
}
}
}
结果:
一件事:您可能不需要将逻辑放入ngAfterViewChecked
循环中.我已经完成了此逻辑,只是向您展示了它是如何工作的.如果您实际上将代码放入将在呈现所有内容时执行的函数中,那么您可以确定placeHolderRef
不是null或未定义.
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.
这篇关于角度HTML选择器的字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!