[英]Angular - Assign value if the property exists
Assign the value if the 'rowData' property exists.如果存在“rowData”属性,则分配该值。 Can we do like below?
我们可以像下面这样吗?
if(this.tableObj.hasOwnProperty('rowData')) {
this.tableObj.rowData = this.defVal.rowData;
}
Getting the below error when I try this.尝试此操作时出现以下错误。 that too inside the if condition.
这也在 if 条件内。
Property 'rowData' does not exist on type '{}'.
UPDATED更新
@Input() tableObj: {};
defVal: {
rowData: [1,2,3]
};
ngOnInit() {
}
reset() {
if( this.tableObj.rowData !== undefined) {
this.tableObj.rowData = this.defVal.rowData;
}
}
Build Error构建错误
error TS2339: Property 'rowData' does not exist on type 'never'.
Yes you can.是的你可以。 Few other ways to do this:
很少有其他方法可以做到这一点:
if ('rowData' in this.tableObj) {
}
Or或者
if (this.tableObj.rowData) {
}
And also the way you mentioned:还有你提到的方式:
if (this.tableObj.hasOwnProperty('rowData')) {
}
Personally I like the first one the most, it explains itself pretty well in my opinion which helps readability.就我个人而言,我最喜欢第一个,我认为它很好地解释了自己,这有助于提高可读性。
EDIT:编辑:
I'm not entirely sure what you're trying to do, the rowData is an array, are you trying to see if a certain item in the array exists as a property in the object?我不完全确定您要做什么,rowData 是一个数组,您是否想查看数组中的某个项目是否作为 object 中的属性存在?
If you want to access a certain item in the array you need to specify the index, like this:如果要访问数组中的某个项目,则需要指定索引,如下所示:
rowData[0]
0 is the first index of the array. 0 是数组的第一个索引。 Which in your case will be accessing the first value which is 1. Then to access the next one it'd be rowData[1] etc.
在您的情况下,将访问第一个值 1。然后访问下一个值,它将是 rowData[1] 等。
So your code should look something like this:所以你的代码应该是这样的:
if (this.tableObj[this.rowData[0]] !== undefined) {
this.tableObj[this.rowData[0]] = this.defVal.rowData;
}
To avoid the error you can try the below code in your if condition.为避免错误,您可以在 if 条件下尝试以下代码。
if(this.tableObj && this.tableObj.rowData !== undefined){
this.tableObj.rowData = this.defVal.rowData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.