Angular中能否通过属性名动态调用类的get/set方法
Angular中实现类动态get/set方法的可行性说明
首先明确结论:这种动态调用的实现方式完全可行,它本质是TypeScript/JavaScript自带的对象动态成员查找能力,和Angular框架无强绑定,直接在原User类上扩展通用方法即可满足需求。
实现核心逻辑
不管传入的是纯属性名(如name)还是完整的get/set方法名(如setName、getName),实现逻辑都做三层兼容:
- 若入参本身是完整的方法名(以
get/set开头),直接匹配类上的对应方法执行 - 若入参是纯属性名,自动按照「get/set + 首字母大写的属性名」的规则拼接成完整方法名,再匹配执行
- 增加方法存在性校验,找不到对应方法时抛出明确错误,避免静默失败的隐蔽问题
改造后的User类完整代码
export class User { name: string; age: number; // 原有业务get/set方法保持不变 getName(): string { return this.name; } setName(name: string): void { this.name = name; } getAge(): number { return this.age; } setAge(age: number): void { this.age = age; } // 新增通用动态赋值方法 setMethod(propOrMethodName: string, value: any): void { let methodName = propOrMethodName; // 入参不是完整set方法名时,自动拼接标准方法名 if (!propOrMethodName.startsWith('set')) { methodName = `set${propOrMethodName.charAt(0).toUpperCase()}${propOrMethodName.slice(1)}`; } if (typeof this[methodName] === 'function') { this[methodName](value); return; } throw new Error(`类上不存在可执行的赋值方法:${methodName}`); } // 新增通用动态取值方法 getMethod(propOrMethodName: string): any { let methodName = propOrMethodName; // 入参不是完整get方法名时,自动拼接标准方法名 if (!propOrMethodName.startsWith('get')) { methodName = `get${propOrMethodName.charAt(0).toUpperCase()}${propOrMethodName.slice(1)}`; } if (typeof this[methodName] === 'function') { return this[methodName](); } throw new Error(`类上不存在可执行的取值方法:${methodName}`); } }
实际调用效果
和你预期的使用方式完全匹配:
const user = new User(); // 传入纯属性名,自动匹配setName完成赋值 user.setMethod('name', 'John'); // 也支持直接传入完整set方法名 user.setMethod('setAge', 28); // 传入纯属性名,自动匹配getName完成取值 const exampleName = user.getMethod('name'); // 返回值为'John' // 也支持直接传入完整get方法名 const exampleAge = user.getMethod('getAge'); // 返回值为28
兼容性说明
这套实现没有依赖任何Angular专属API,不管是在业务实体、服务类、还是Angular动态表单场景下做批量取值、赋值,都可以正常使用。后续如果User类新增了符合命名规范的get/set方法(比如新增email属性对应getEmail/setEmail),不需要修改通用的动态方法逻辑,就能直接适配新的属性操作。
内容的提问来源于stack exchange,提问作者Hasan Kaan TURAN
相关产品推荐
相关产品推荐

