【问题标题】:String interpolation for angular HTML selector角度 HTML 选择器的字符串插值
【发布时间】:2019-04-13 01:29:31
【问题描述】:

我有许多具有不同选择器的组件,例如 app-protocol、app-inspection、app-generalview 等。我希望渲染的组件基于一个变量,例如:

在打字稿中

view = 'protocol'; // or inspection or generalview

在 HTML 中

<app-{{view}}> </app-{{view}}>

<div [innerHTML] = "'<app-{{view}}>'"> </div>

然而,这两个 HTML 示例都不起作用。我知道我可以使用 *ngSwitch 但我可能有很多情况并且想知道是否有办法避免这样做。非常感谢。

【问题讨论】:

  • 也许将选择器切换到[app-protocol](等等),并将标签用作&lt;div app-protocol&gt;?从未尝试过,但选择器是 querySelector 字符串,所以这应该可以工作

标签: html angular rendering


【解决方案1】:

您可以使用componentFactoryResolverviewContainerRef 动态地渲染组件。

这是一个简单的例子,我创建了一个名为 Cmp1Component 的组件,它将被动态渲染。

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();
      }
    }

}

结果:

一件事:您可能不需要将逻辑放入ngAfterViewChecked 循环中。我做了这个逻辑只是为了向你展示它是如何工作的。如果你真的把代码放在一个函数中,当所有东西都被渲染时就会执行,那么你肯定知道placeHolderRef不是空的或未定义的。

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2019-03-24
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多