简体   繁体   English

角度:在[innerHtml]中绑定变量

[英]Angular: bind variables inside [innerHtml]

I am trying to bind data inside a div using [innerHtml]. 我正在尝试使用[innerHtml]将div中的数据绑定。 How to notify angular to use the variables instead of the raw text. 如何通知angular使用变量而不是原始文本。 Here is my setup : 这是我的设置:

<div *ngFor="let data of someData">
    <div *ngFor="let odata of someOtherData;trackBy:id">
        <div [innerHTML]="odata.template | pipeToSanitize"></div>
    </div>
</div>

The data looks like this : 数据如下:

someOtherData = [{
                    'id': 1,
                    'template': '<div class="{{data.class}}"><md-icon>{{data.icon}}</md-icon></div>'
                }, 
                {
                    'id': 2,
                    'template': '<div>{{data.timestampStr}}</div>'
                }, 
                {
                    'id': 3,
                    'template': '<div>{{data.message}}</div>'
                }]

someData = [{
               'message': 'Message 1',
               'timestampStr': '2016/12/13 09:25:00',
               'class': 'events-warn-color',
               'icon': 'warning'
            }, 
           {
               'message': 'Message 2',
               'timestampStr': '2016/12/13 10:36:00',
               'class': 'events-warn-color',
               'icon': 'warning'
           }];

Now I am getting {{data.icon}},etc. 现在我得到了{{data.icon}}等。 as it is. 照原样。 How can replace this with the contents from 'someOtherData' object. 如何用'someOtherData'对象的内容替换它。 Thanks in advance 提前致谢

You have to create compiler directive to evaluate the template string: 您必须创建编译器指令来评估模板字符串:

compile.directive.ts compile.directive.ts

  @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;
    }
  }

Template 模板

<div *ngFor="let data of someData">
    <div *ngFor="let odata of someOtherData;">
          <ng-container *compile="odata.template; context:{data:data}"></ng-container>
    </div>
</div>

You still need to deal with angular material module , I haven't impliment that to my online example, just check compile direactive comment 您仍然需要处理角材料模块,我并没有暗示对我的在线示例,只需要检查编译命令注释即可

stackblitz template compile stackblitz模板编译

Check this Angular2, evaluate template from string inside a component 检查此Angular2,从组件内部的字符串评估模板

Why use [innerHTML] ? 为什么要使用[innerHTML]

Try 尝试

<div>{{odata.template | pipeToSanitize}}</div>

EDITED: can you try this too: 编辑:您也可以尝试以下方法:

<div *ngFor="let data of someData">
    <div *ngFor="let odata of getData(data);trackBy:id">
        <div [innerHTML]="odata.template | pipeToSanitize"></div>
    </div>
</div>

getDataFormated(data:any):any{
return [{
                    'id': 1,
                    'template': '<div class="{{data.class}}"><md-icon>{{data.icon}}</md-icon></div>'
                }, 
                {
                    'id': 2,
                    'template': '<div>{{data.timestampStr}}</div>'
                }, 
                {
                    'id': 3,
                    'template': '<div>{{data.message}}</div>'
                }]
}

[innerHtml] is great option in most cases, but it fails with really large strings or when you need hard-coded styling in html. 在大多数情况下,[innerHtml]是一个不错的选择,但是对于很大的字符串或当您需要html中的硬编码样式时,它会失败。

you can check for answers in the following to get a good idea. 您可以在下面检查答案,以获得一个好主意。 Specially Piotrek's answer 特别是Piotrek的答案

Angular HTML binding 角度HTML绑定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM