我正在使用angular 7,并试图在子组件中做一些事情:使用input属性,可以在对象的第一层或更深。
我的子组件有这段代码:
if (this.values.filter(obj => obj[this.matchPropertyName] === $event[i].id).length === 0) {
...
}
这个地方。matchPropertyName是我的输入(可以是'id', 'myProperty.id',…)
对于单个级别(obj.id),此代码有效。然而,我有时需要从更深的层次(obj.myProperty.id)使用,它不起作用。我该怎么做呢?
如果还不够清楚,请告诉我。
我使用的是angular 7和typescript 3.2.4
我不认为有一个内置的解决方案,但你可以利用一个简单的split
和reduce
。例如:
const value = this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
当this.matchPropertyName="myProperty.id"
时,给出obj.myProperty.id
的值
Stackblitz
在你的例子中,你可以这样写:
const theValue = this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
if (this.values.filter(obj => theValue === $event[i].id).length === 0) {
...
}
OP的最终结果:
myEventListener($event) {
if (this.values.filter(obj => this.resolveProperty(obj) === $event[i].id).length === 0) {
...
}
}
resolveProperty(obj) {
return this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
}