[英]Assigning a value to variable shows read only error
component.ts组件.ts
export class AppComponent {
details:{a: boolean,
b:boolean,
c:boolean,
x:number} = {
a: false,
b: false,
c: false,
x: 0,
};
public get value(): number {
const numbermap = { a: 1, b: 2, c: 3 } //value of checkboxes;
return Object.entries(this.details)
// get only the entries with true value
.filter(([_key, value]) => value)
// map the keys having true to an array of numbers
.map(([key]) => numbermap[key])
// requred for preventing error from reduce if none selected `[].reduce()`
.concat(0)
// sum the numbers with reduce
.reduce((prev = 0, curr) => prev + curr)
}
submit() {
this.value = this.details.x; //Assigning value to variable
console.log(this.value);
}
}
What i'm doing is I've created cheeckboxes a,b,c which holds a value 1 2 3 respectively.我正在做的是我创建了复选框 a,b,c 分别持有一个值 1 2 3 。 When true each checkboxes value gets added.
当为 true 时,每个复选框的值都会被添加。 But when I'm trying to assign this value to x (in details array) I get an error "x is a readonly property".
但是,当我尝试将此值分配给 x(在 details 数组中)时,我收到一个错误“x 是只读属性”。
Your value
getter method's name is colliding with a value
property on the instance.您的
value
getter 方法的名称与实例上的value
属性冲突。 You could:你可以:
Choose a different name, eg, use getValue
instead of a value
getter, allowing you to use this.value
as a normal property选择不同的名称,例如,使用
getValue
而不是value
getter,允许您使用this.value
作为普通属性
Add a setter for value
as well, eg:也为
value
添加一个 setter,例如:
set value(newValue) { this._value = newValue; }
(and define the type for this._value
) (并定义
this._value
的类型)
Since the only place the value looks to be used is in submit
, you could remove the assignment to the instance entirely and use a local variable instead, if that's what you're intending:由于该值看起来被使用的唯一位置是在
submit
中,因此您可以完全删除对实例的分配并改用局部变量,如果这是您的意图:
submit() { const val = this.details.x; console.log(val); }
You need to define a set for the job of assigning values to value
.您需要为将值分配给
value
的工作定义一个集合。
Example:例子:
public set value(new_value: number) {
this.details.x = new_value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.