如何配置Angular 10让未知绑定、缺失输入属性时抛出错误
Angular 10 模板输入属性编译校验配置方案
配置修正步骤
首先修正tsconfig.json配置,注意angularCompilerOptions必须和compilerOptions平级,不能嵌套在compilerOptions内部,这是多数人配置不生效的核心原因。修正后的配置如下:
{ "compilerOptions": { // 保留原有其他配置,确保开启以下两项 "strictNullChecks": true, "strict": true }, // 以下配置放在tsconfig根层级,不要写到compilerOptions里 "angularCompilerOptions": { "enableIvy": true, "strictTemplates": true, "strictInjectionParameters": true, // 移除原配置里的fullTemplateTypeCheck: true,该项是旧版View Engine的校验配置,在Ivy下会和strictTemplates冲突导致校验失效 // 显式开启严格模板的子校验开关,避免被默认配置覆盖 "strictInputTypes": true, "strictInputAccessModifiers": true, "strictNullInputTypes": true, "fullTemplateTypeCheck": false } }
两类场景的校验生效说明
1. 绑定组件不存在的属性(如示例中拼写错误的naame)
上述配置生效后,编译时会直接抛出Can't bind to 'naame' since it isn't a known property of 'person'的错误。
如果仍未报错,排查以下问题:
- 确认
PersonComponent已经在对应模块的declarations数组中声明,未声明的组件会被编译器识别为未知元素,不会触发输入属性校验 - 检查模板中是否用
$any()包裹了组件或绑定值,该写法会绕过所有模板类型校验 - 执行
ng build确认生产构建下是否报错,部分旧版Angular CLI 10在dev serve模式下会延迟全量模板检查
2. 未传递必填输入属性(如示例中缺失的name绑定)
Angular 10 没有原生的必填输入装饰器标记,需要通过类型约束触发校验:
- 对需要必填的
@Input()属性,不要设置初始值,不要在类型定义中包含undefined,也不要用可选属性标记?,示例组件写法调整为:
@Component({ selector: "person" }) export class PersonComponent { @Input() age: number; // 不要写name?: string,也不要给name设默认值,明确类型为string @Input() name: string; }
配合开启的strictNullInputTypes和strictNullChecks,未传name绑定时,编译器会检测到属性值为undefined,和string类型不匹配,抛出类型错误。
注意:如果给输入属性设置了默认值(如
name: string = ''),即使不传绑定也不会触发报错,因为默认值已经满足类型要求。如果需要更直观的必填输入校验能力,可升级到Angular 16+版本,原生支持@Input({ required: true })写法,编译器会直接识别未传必填输入的问题,不需要依赖类型推断。
内容的提问来源于stack exchange,提问作者user2475269
相关产品推荐
相关产品推荐

