Angular组件外声明的const常量无法传递到模板渲染怎么解决
问题原因
Angular 组件模板默认仅能访问组件类内部暴露的属性与方法,你定义在export class MyComponent外部的const MIN_PW属于当前模块的顶层变量,没有挂载到组件实例上,因此模板无法读取到该值,才会出现插值位置为空、UI展示不完整的问题。
你之前将变量定义在export class内部时可以正常运行,正是因为该变量属于类的属性,模板有权限访问。
解决方案
如果要保留「将常量定义在组件外部」的写法,只需要在组件类内部新增一行对该常量的引用,将其绑定为类的公开只读属性即可,修改后的组件代码如下:
const MIN_PW = 12; export class MyComponent implements OnInit { // 新增此行,将外部常量绑定为类属性 readonly MIN_PW = MIN_PW; myFormGroup = this.formBuilder.group({ password: new FormControl(null, [Validators.required, Validators.minLength(MIN_PW)]), // 其他配置 }) }
修改后原模板代码不需要调整,即可正常展示MIN_PW的数值。
如果这个常量仅在当前组件中使用,也可以直接将其定义为类的只读属性,无需放到组件外部:
export class MyComponent implements OnInit { readonly MIN_PW = 12; myFormGroup = this.formBuilder.group({ password: new FormControl(null, [Validators.required, Validators.minLength(this.MIN_PW)]), // 其他配置 }) }
内容的提问来源于stack exchange,提问作者Bodrov
相关产品推荐
相关产品推荐

