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

Angular模板给组件@Input传含单引号的JSON串编译报错如何解决?

Angular模板@Input绑定含单引号字符串的解决方案

问题根因

Angular的HTML模板会先经过HTML解析器处理,再解析内部的绑定表达式,直接用\'转义单引号会被HTML解析器拦截,无法正确传递到Angular表达式层,所以会触发编译错误。

可行方案

方案1(最推荐):将配置对象定义在组件TS文件中,模板直接绑定变量

这种方案完全避免模板内的转义冲突,同时符合Angular最佳实践,降低模板逻辑复杂度,便于后期维护。
组件对应的.ts文件代码:

// 组件类中定义配置对象
public componentInfo = {
  id:'wt_tab_206_000000010',
  value:'LoadData\'new', // TS中正常转义单引号即可
  disabled:false,
  readonly:false
}

模板绑定代码:

<my-component id="wt_tab_206_000000010wrap" class="form-group  inlineblock"
                    [info]="componentInfo"
                    filterFields="N"></my-component>

方案2:模板内使用HTML实体编码替换单引号

单引号的HTML实体编码为&#39;,直接替换字符串中的单引号即可正常解析:

<my-component id="wt_tab_206_000000010wrap" class="form-group  inlineblock"
                    [info]="{'id':'wt_tab_206_000000010','value':'LoadData&#39;new','disabled':false,'readonly':false}"
                    filterFields="N"></my-component>

方案3:模板内使用Unicode转义单引号

在绑定表达式中使用单引号的Unicode编码\u0027替换直接书写的单引号:

<my-component id="wt_tab_206_000000010wrap" class="form-group  inlineblock"
                    [info]="{'id':'wt_tab_206_000000010','value':'LoadData\u0027new','disabled':false,'readonly':false}"
                    filterFields="N"></my-component>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:36:03