Реализация рассылки электронной почты с использованием Angular2
Я пытаюсь создать инструмент для рассылки электронной почты, который включает в себя интерфейс для управления контентом и отправки HTML в виде электронной почты.
Я пытаюсь сохранить один угловой шаблон для пользовательского интерфейса и отправить его по электронной почте. Этот шаблон также имеет некоторые IE
конкретные комментарии, чтобы заставить его работать в перспективе. Шаблон может содержать различные HTML и стиль, но данные остаются теми же.
Это то, что я начал. https://plnkr.co/edit/NiYAopyCyFQyBK4aER5v?p=preview
- Задача, с которой я сталкиваюсь, заключается в том, как скомпилировать html с данными и визуализировать в пользовательском интерфейсе
- Как получить чистый HTML без
ngif ngfor comments
отправить его по электронной почте.
********************** Обновление 21.09.2017, 20:00 *********************
Был в состоянии решить первый вызов. Обновлен плнкр
********************** Обновление 23.09.2017, 20:00 *********************
Искал правильный способ compiling html string with data
, Пришлось пойти с этим подходом с некоторыми ограничениями https://github.com/tomalex0/compile-ng2-template
Я ищу что-то похожее на этот https://www.npmjs.com/package/angular-template в angular2.
1 ответ
Был в состоянии заставить это работать как я ожидал. Пришлось также перенести определенную логику на серверную сторону.
Оформить заказ плнкр и гитхуб
https://plnkr.co/edit/NiYAopyCyFQyBK4aER5v?p=preview
https://github.com/tomalex0/compile-ng2-template
import { Component, Component,
ViewChild, ViewContainerRef, ComponentRef, NgModuleRef,ElementRef,
Compiler, ComponentFactory, NgModule, ModuleWithComponentFactories, ComponentFactoryResolver } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('container', { read: ViewContainerRef })
container: ViewContainerRef;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private compiler: Compiler
) {
}
htmlstring : string;
data = {
title : "Newsletter",
list : [{
name : "One"
},{
name : "Two"
}],
enabled : true
};
templateArr = [{
name : "t1",
displayName : "Template1",
html : `<div>
<h1>Template 1</h1>
<h2>{{data.title}}</h2> <input name="title" type="text" [(ngModel)]="data.title" />
<div>
<li *ngFor="let listitem of data.list; let index = index">
List item {{listitem.name}}
</li>
</div>
<!--[if (gte mso 9)|(IE)]>
<div>Internet Explorer</div>
<![endif]-->
<div *ngIf="data.enabled">Enabled</div>
<div *ngIf="!data.enabled">Not Enabled</div>
</div>`
},{
name : "t2",
displayName : "Template2",
html : `<div>
<h1>Template 2</h1>
<h2>{{data.title}}</h2> <input name="title" type="text" [(ngModel)]="data.title" />
<div>
<li *ngFor="let listitem of data.list; let index = index">
List item {{listitem.name}}
</li>
</div>
<!--[if (gte mso 9)|(IE)]>
<div>Internet Explorer</div>
<![endif]-->
<div *ngIf="data.enabled">Enabled</div>
<div *ngIf="!data.enabled">Not Enabled</div>
</div>`
}]
name = 'Angular Newsletter';
loadTemplate (item) {
console.log(item.html)
let metadata = {
selector: `runtime-component-dynamic`,
template: item.html
};
let factory = this.createComponentFactorySync(this.compiler, metadata);
if (this.componentRef) {
this.componentRef.destroy();
this.componentRef = null;
}
this.componentRef = this.container.createComponent(factory);
this.componentRef.instance.data = this.data;
}
private createComponentFactorySync(compiler: Compiler, metadata: Component): ComponentFactory<any> {
let decoratedCmp = Component(metadata)(class { });
@NgModule({ imports: [CommonModule, FormsModule], declarations: [decoratedCmp] })
class RuntimeComponentModule { }
compiler.clearCacheFor(decoratedCmp);
let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
return module.componentFactories.find(f => f.componentType === decoratedCmp);
}
sendMail (){
this.htmlstring = this.componentRef.location.nativeElement.innerHTML;
this.htmlstring = this.htmlstring.replace(/<!--bindings[\s\S]*?(?:-->)/g, '');
}
}
/*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/