Reputation: 69
When the user selects the top left checkbox, it changes the value of every box in the table based on the value of another form control above. If they select any of the others, only the values in that row will change.
So, as of right now, here is how I'm handling these changes:
In my ngOnInit
:
this.form.controls['selectAll']
.valueChanges
.distinctUntilChanged()
.subscribe(data => {
this.selectAll();
});`
and my selectAll
function:
selectAll() {
let depthValue = this.form.controls['depth'].value;
if (this.form.controls['selectAll'].value === true) {
this.form.controls['index44'].setValue(depthValue);
this.form.controls['index4'].setValue(depthValue);
this.form.controls['index5'].setValue(depthValue);
this.form.controls['index6'].setValue(depthValue);
this.form.controls['index7'].setValue(depthValue);
this.form.controls['index8'].setValue(depthValue);
this.form.controls['index9'].setValue(depthValue);
this.form.controls['index10'].setValue(depthValue);
this.form.controls['index13'].setValue(depthValue);
this.form.controls['index14'].setValue(depthValue);
this.form.controls['index15'].setValue(depthValue);
this.form.controls['index16'].setValue(depthValue);
this.form.controls['index17'].setValue(depthValue);
this.form.controls['index18'].setValue(depthValue);
this.form.controls['index19'].setValue(depthValue);
this.form.controls['index20'].setValue(depthValue);
this.form.controls['index21'].setValue(depthValue);
//etc
}
So my question is: Is there an easier/less verbose way of applying the value to all of these boxes so I don't have to have hundreds of lines of code dedicated to simply changing to value of a number box?
Upvotes: 0
Views: 626
Reputation: 19764
It can be done as long as you logically structure your data properly. Based on the given information, we do not know what's the relationship between numbers. The code you've shown us sets indices 4 - 10, 13-21... Why does it skip 11 an 12? If you have some logic in that, you can write it down.
There is nothing Angular-specific that can speed up setting value of abitrary controls, similary to how you have to set values of JavaScript variables yourself.
However, with some clever thinking you can create a nice interface to access those elements, even if there is no logical relationship between them.
To set all elemnts between index4
and index10
, you can use a simple for loop. You can encapsulate it in a function and reuse this function.
// Set a range of controls in the passed form
function setRange(form, from, to) {
for (let i = 4; i <= 10; i++) {
form.controls[`index${i}`].setValue(depthValue);
}
}
// Usage
setRange(this.form, 4, 10)
setRange(this.form, 13, 21)
setRange(this.form, 30, 40)
Of course, you can take this to the next level by processing multiple range at same time, so you might go for an API such as the following.
setRanges(this.form, [[4, 10], [13, 21], [30, 40]])
I leave the implementation to the reader.
Upvotes: 1