【问题标题】:Angular 2 how to compile a template and save the result htmlAngular 2如何编译模板并保存结果html
【发布时间】:2017-04-26 02:19:02
【问题描述】:

好的,现在我必须为电子邮件创建正文。

我需要一个模板,用我已经拥有的数据(js 对象)插入它,并将这个结果 html 字符串放在一个变量中,这样我就可以将此正文发送到一个服务器,该服务器将实际发送电子邮件。

我不确定是否使用其他模板引擎(例如把手)来生成此 html。

有没有办法使用 Angular 2 模板引擎?请记住,我不需要显示它,我只想将它保存在内存中。

如果我不能使用它,我应该使用什么?有没有最知名或推荐的方法?

【问题讨论】:

    标签: angular angular2-template templating


    【解决方案1】:

    不知道你为什么需要它,但这里有一些想法:

    import {Component, NgModule, Input, VERSION, ChangeDetectorRef} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    import {Injectable, ComponentFactoryResolver, ApplicationRef, Injector} from '@angular/core';
    
    @Component({
      selector:'my-cmp',
      template: 'here is {{title}}'
    })
    export class MyComponent {
      @Input() title: string;
    }
    
    @Component({
      selector: 'my-app',
      template: `
        <input #inp>
        <button (click)="create(inp.value)">Create</button>
      `,
    })
    export class App {
      constructor(private componentFactoryResolver: ComponentFactoryResolver,
                  private appRef: ApplicationRef,
                  private injector: Injector) {
      }
    
      create(title) {
        let factory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
        let ref = factory.create(this.injector);
        ref.instance.title = title;
        this.appRef.attachView(ref.hostView);
    
        console.log(ref.location.nativeElement);
    
        this.appRef.detachView(ref.hostView);
      }
    }
    
    @NgModule({
      imports: [ BrowserModule ],
      declarations: [ App , MyComponent],
      entryComponents: [MyComponent],
      bootstrap: [ App ]
    })
    export class AppModule {}
    

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 2016-04-20
      • 1970-01-01
      • 2021-04-12
      • 2017-02-26
      • 1970-01-01
      • 2016-02-23
      • 2016-01-20
      • 2017-06-30
      相关资源
      最近更新 更多