ngx-formly中JSON字段定义无法渲染model/formState只读信息求助
解决ngx-formly中JSON配置无法解析model字段的问题
ngx-formly和旧版angular-formly的template字段处理逻辑不同,直接写{{model.status}}会被当成纯文本输出,因为动态JSON里的模板不会被Angular自动编译。下面提供两种可行的解决方法:
方案一:用expressionProperties动态生成模板(简单场景首选)
不需要额外创建组件,直接修改JSON配置即可:
"fieldGroup": [ { "template": "", "expressionProperties": { "template": "`Status: ${model.status}`" } } ]
原理是expressionProperties里的表达式会被ngx-formly解析执行,通过模板字符串把model的status值直接拼入模板内容,最终渲染出预期的文本。
方案二:自定义HTML字段类型(复杂模板场景)
如果需要展示多字段、带样式的复杂HTML模板,可以自定义通用的HTML字段类型:
- 创建HTML字段组件
import { Component } from '@angular/core'; import { FieldType, FieldTypeConfig } from '@ngx-formly/core'; @Component({ template: '<div [innerHTML]="to.content | safeHtml"></div>', }) export class HtmlFieldType extends FieldType<FieldTypeConfig> {}
- 创建安全HTML管道,绕过Angular的XSS安全拦截
import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Pipe({ name: 'safeHtml' }) export class SafeHtmlPipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform(value: string): SafeHtml { return this.sanitizer.bypassSecurityTrustHtml(value); } }
- 在模块中注册自定义字段和管道
import { NgModule } from '@angular/core'; import { FormlyModule } from '@ngx-formly/core'; import { HtmlFieldType } from './html-field.type'; import { SafeHtmlPipe } from './safe-html.pipe'; @NgModule({ declarations: [HtmlFieldType, SafeHtmlPipe], imports: [ FormlyModule.forRoot({ types: [ { name: 'html', component: HtmlFieldType }, ], }), ], }) export class AppModule {}
- 在JSON配置中使用该自定义类型
"fieldGroup": [ { "type": "html", "templateOptions": { "content": "Status: {{model.status}}<br>创建时间: {{model.createdAt}}" } } ]
内容的提问来源于stack exchange,提问作者Ulf
相关产品推荐
相关产品推荐

