我正在尝试使用 [innerHtml] 在 div 内绑定数据。如何通知 Angular 使用变量而不是原始文本。这是我的设置:
<div *ngFor="let data of someData">
<div *ngFor="let odata of someOtherData;trackBy:id">
<div [innerHTML]="odata.template | pipeToSanitize"></div>
</div>
</div>
数据如下:
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'
}];
现在我得到了 {{data.icon}} 等。就这样。如何将其替换为“someOtherData”对象中的内容。提前致谢
您必须创建编译器指令来评估模板字符串:
编译指令.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>
您仍然需要处理角度材料模块,我没有在我的在线示例中暗示这一点,只需检查编译直接注释
stackblitz模板编译 https://stackblitz.com/edit/angular-template-compile
检查这个Angular2,从组件内的字符串评估模板 https://stackoverflow.com/questions/44077994/angular2-evaluate-template-from-string-inside-a-component
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)