如何在Angular中将{{...}} HTML代码与innerHtml绑定/渲染

3

我试图使用innerHTML绑定/渲染HTML内容,但无法在Angular中渲染{{...}}。

以下是代码:

<div [innerHtml]="TestString"></div>

test = " HTML Content ";
TestString = "<div>This is test code, i am trying to bind/render {{ test }} code with angular..,</div>";

结果

这是测试代码,我正在尝试将 {{ test }} 代码与 Angular 绑定/渲染,

但未能绑定/渲染 test 变量的值....


您也可以在 .ts 文件中连接字符串 TestString = '<div>This is test code, i am trying to bind/render' + this.test +' code with angular..,</div>' - Ilija Iličić
1个回答

7
尝试这种方式:
test = " HTML Content ";
TestString = `<div>This is test code, i am trying to bind/render ${this.test} code with angular..,</div>`

https://stackblitz.com/edit/angular-ckxsp8?file=src/app/app.component.ts

如果你想在组件内部从字符串中评估模板,你可以创建自己的指令来完成:

compile.directive.ts

import {
  Compiler, NgModule, Component, Input, ComponentRef, Directive, 
  ModuleWithComponentFactories, OnChanges, Type,
  ViewContainerRef
} from '@angular/core';
import { CommonModule } from '@angular/common';

@Directive({
  selector: '[compile]'
})
export class CompileDirective implements OnChanges {
  @Input() compile: string;
  @Input() compileContext: any;

  compRef: ComponentRef<any>;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {}

  ngOnChanges() {
    if(!this.compile) {
      if(this.compRef) {
        this.updateProperties();
        return;
      }
      throw Error('You forgot to provide template');
    }

    this.vcRef.clear();
    this.compRef = null;

    const component = this.createDynamicComponent(this.compile);
    const module = this.createDynamicModule(component);
    this.compiler.compileModuleAndAllComponentsAsync(module)
      .then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
        let compFactory = moduleWithFactories.componentFactories.find(x => x.componentType === component);

        this.compRef = this.vcRef.createComponent(compFactory);
        this.updateProperties();
      })
      .catch(error => {
        console.log(error);
      });
  }

  updateProperties() {
    for(var prop in this.compileContext) {
      this.compRef.instance[prop] = this.compileContext[prop];
    }
  }

  private createDynamicComponent (template:string) {
    @Component({
      selector: 'custom-dynamic-component',
      template: template,
    })
    class CustomDynamicComponent {}
    return CustomDynamicComponent;
  }

  private createDynamicModule (component: Type<any>) {
    @NgModule({
      // You might need other modules, providers, etc...
      // Note that whatever components you want to be able
      // to render dynamically must be known to this module
      imports: [CommonModule],
      declarations: [component]
    })
    class DynamicModule {}
    return DynamicModule;
  }
}

使用方法:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent {

  name = 'Product Name :'
  price = '3'
  template: string = `{{ name }} <b>{{ price }}$</b>`;
}

HTML:

<div class="product">
  <ng-container *compile="template; context: this"></ng-container>
</div>

示例:https://stackblitz.com/edit/angular-eipbup?file=src%2Fapp%2Fapp.component.html


想要迭代对象。 - Sunil Pune
请查看此链接:https://stackblitz.com/edit/angular-xhbmhf?file=src/app/app.module.ts 希望对您有所帮助。 - BartoszTermena
谢谢亲爱的帮助我,我是 Angular 的新手...再次感谢...祝你愉快。 - Sunil Pune
1
嗨@SunilPune,你能解决这个问题吗?或者你有其他解决方案吗? - jecorrales
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接