首页 > 解决方案 > 如何在 Angular 中以编程方式检查组件是否具有属性定义?

问题描述

我在 Angular 中有一个组件的属性,如下所示:

export class CarComponent implements OnInit {
  partNumber: number;

  checkIfItHasAPartNumberProperty() {
      return this.hasAProperty('partNumber');
  }

hasAProperty 检查此类是否包含按字符串名称定义的属性的 Angular 等效项是什么,例如。“零件号”?

这不是关于获取“partNumber”值的问题,也不是直接检查它是否具有属性“partNumber”的问题,而是以编程方式检查组件是否具有给定名称的属性(通过字符串)。

标签: angular

解决方案


 const obj = this as object;
 obj.hasOwnProperty('prop')

Cast this to object and you should be able to call hasOwnProperty on it

EDIT This wont work on properties that haven't been initialized. For that case (if possible in your scenario) initialize the property with null and the above code will work


推荐阅读