You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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字段类型:

  1. 创建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> {}
  1. 创建安全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);
  }
}
  1. 在模块中注册自定义字段和管道
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 {}
  1. 在JSON配置中使用该自定义类型
"fieldGroup": [
  {
    "type": "html",
    "templateOptions": {
      "content": "Status: {{model.status}}<br>创建时间: {{model.createdAt}}"
    }
  }
]

内容的提问来源于stack exchange,提问作者Ulf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 21:00:10