как связать / отобразить {{...}} html код с внутренним Html в angular - PullRequest
1 голос
/ 06 марта 2020

Я пытаюсь связать / отобразить html содержимое с внутренним 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 ..,

not значение тестовой переменной привязки / рендеринга ....

1 Ответ

6 голосов
/ 06 марта 2020

Попробуйте следующим образом:

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>

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...