【问题标题】:Custom Tag Name for Angular dynamic ComponentAngular 动态组件的自定义标签名称
【发布时间】:2019-03-29 13:00:02
【问题描述】:

我有一个简单的组件

@Component({
  selector: '[my-component]',
  template: `<i>1</i><p>content</p><b>2</b>`
})
export class MyComponent {
  public tagName: string;
}

另一个实例化第一个:

export class AppComponent implements OnInit {
 @ViewChild("myContainer", { read: ViewContainerRef }) container;

  constructor(
      private viewContainer: ViewContainerRef,
      private resolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
    this.container.clear();
    const compFactory = this.resolver.resolveComponentFactory(MyComponent);
    const componentRef = this.container.createComponent(compFactory);
    componentRef.instance.tagName = 'span';
  }
}

AppComponent的模板只是

<template #myContainer></template>

,所以输出是

<div my-component><i>1</i><p>content</p><b>2</b></div>

我要做的是在实例化过程中自定义MyComponent 模板,并将其p 标记替换为名称应为tagName 的标记。在执行AppComponent.ngOnInit 方法时,我知道MyComponent 创建之前的标签名称。

我要解决的另一项任务是MyComponent 包装标签名称定制。将&lt;div my-component&gt;... 替换为&lt;span my-component&gt;...,其中“span”是所需的标签名称,也称为AppComponent.ngOnInit

那么是否有可能以编程方式提供这样的自定义并获得以下信息:

<span my-component><i>1</i><span>content</span><b>2</b></span>

tagName 可以是任何允许的 HTML 标记,并且 ngIf/Switch 不是一个选项。我为快速潜水创建了演示:https://stackblitz.com/edit/angular-zngyoa

【问题讨论】:

    标签: html angular angular-components angular-dynamic-components


    【解决方案1】:

    对于问题 1,使用字符串正则表达式将 'p' 替换为 'span' 标记。应该在 ngAfterViewInit 生命周期方法中完成。

    import { Component, OnInit, AfterViewInit, ElementRef } from '@angular/core';
    
    @Component({
      selector: '[my-component]',
      template: `<i>1</i><p>content</p><b>2</b>`
    })
    export class MyComponent implements AfterViewInit, OnInit{
      public tagName: string;
    
      constructor(private elementref: ElementRef){}
    
      ngOnInit(){}
    
      ngAfterViewInit(){
        if(this.tagName && this.elementref){
          let htmlcontent = this.elementref.nativeElement.innerHTML;
          htmlcontent = htmlcontent.replace(/p/g, 'span');
          this.elementref.nativeElement.innerHTML = htmlcontent;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-05
      • 2016-11-19
      • 2018-02-01
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 2016-08-03
      相关资源
      最近更新 更多