Home > Software design >  How can i achieve the percentage splitting accordingly in angular
How can i achieve the percentage splitting accordingly in angular

Time:02-04

I am trying to achieve this with ANGULAR i want to split the percentage as shown in image if the txtBox1 has 75% i want remining txt2,txt3 split the reming 25% and if i change the txt1 to 50% i want other to be 25% and 25% like dynamically splitting the values might vary

This is what i tried I know its not much Please refer the image

enter image description here

enter image description here

Is it possible to achieve this ? please help me out

CodePudding user response:

The logic could be as follows:

  const restPercentages = 100 - this.form.controls.textbox1.value;
  this.form.controls.textbox2.setValue(restPercentages/2);
  this.form.controls.textbox3.setValue(restPercentages/2);

I don't know the moment you would like to make such check. Maybe on blur event of textbox1? and disabling both textbox2, textbox3 are the way to go.

CodePudding user response:

Here is a solution that always updates the other two controls when a given control is edited and then blurred. There are optimisations and validation checks that could/should be implemented to improve the solution, but hopefully this is sufficient to demonstrate the concept

interface TextForm {
  textbox1: FormControl<string>;
  textbox2: FormControl<string>;
  textbox3: FormControl<string>;
}

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  template: `
    <form [formGroup]="form">
      <div>
        <input type="text" formControlName="textbox1" (blur)="calculateRemainders('textbox1')" />
        <hr />
      </div>
      <div>
        <input type="text" formControlName="textbox2" (blur)="calculateRemainders('textbox2')" />
        <hr />
      </div>
      <div>
        <input type="text" formControlName="textbox3" (blur)="calculateRemainders('textbox3')" />
        <hr />
      </div>
    </form>
  `,
})
export class App {
  form: FormGroup<TextForm>;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.form = this.fb.group({
      textbox1: [''],
      textbox2: [''],
      textbox3: [''],
    });
    this.applyInitValues();
  }

  applyInitValues() {
    let count =  Object.keys(this.form.controls).length;
    let equality = (100 / count).toFixed(1);

    this.form.setValue({
      textbox1: equality,
      textbox2: equality,
      textbox3: equality,
    });
  }

  calculateRemainders(editedControlKey: keyof TextForm) {
    // Get array of controls as [[controlKey1, control1], [controlKey2, control2], [controlKey3, control3]]
    // Sort to make sure that the first index is the control that was edited
    const controls: [string, FormControl<string>][] = Object.entries(this.form.controls).sort(([controlKey]) => controlKey === editedControlKey ? 1 : 0);

    // Ensure the first control value is set to 1 decimal place and calculate the remaining 2 values (also to 1.d.p)
    const editedControlValue: number = this.toOneDecimalPlace(Number(this.form.get(editedControlKey).value));
    const firstRemainder: number = this.toOneDecimalPlace((100 - editedControlValue) / 2);
    const secondRemainder: number = this.toOneDecimalPlace(100 - editedControlValue - firstRemainder);

    // Apply the updated values to each control (as strings)
    controls[0][1].setValue(`${editedControlValue}`);
    controls[1][1].setValue(`${firstRemainder}`);
    controls[2][1].setValue(`${secondRemainder}`);
  }

  toOneDecimalPlace(number: number) {
    return Math.round(number * 10) / 10
  }
}

StackBlitz

  • Related