0
votes

how to store json data with angular reactive form , in form control .

for example

json coming from server  = [{
ctrlname : controlName1,
type : "Link",
unit:"M"

},{
ctrlname : controlName2,
type : "Date",
unit:"L"

}]

// making FormGroup

  let a = new formGroup({
    controlName1 : new FormControl(''),
    controlName2 : new FormControl(''),
    })

i want to store type,unit property also with formcontrol so how can i do it ? when making formgroup with formcontrol?

so when i get the value of formcontrol like this.myformgroup.controls['controlName1'] so i can get the unit and type also from this ? so how to store unit and type json while making the formcontrol

1
Define "store"...Brandon
@Brandon updated the question please checkCoffeeMaster
Provided the "ctrlname" value is unique, you could use .find() on the array of values to get the one that corresponds to the control name. From there you could maintain your own array of objects that has the form input value plus the other two values.Brandon
@Brandon yes i am doing the same method but it would be more optimised and good if we can store data with formcontrol as i have to use .find method everywhere . so is there anyway that we can store json data with formcontrol ?CoffeeMaster
The FormControl doesn't have any additional properties you could bind the extra values to.Brandon

1 Answers

2
votes

Per the comments, one way you can do this is to store these extra pieces of data in a ViewModel property and update them as your inputs change...

interface IFormData: {
  [controlName: string]: {
    value?: string;
    type?: string;
    unit?: string;
  }
}

@Component(...)
export class YourComponent implements OnInit, OnDestroy {

  control1Subscription: Subscription;
  data: IFormData = {
    controlName1: {},
    controlName2: {},
  };
  form: FormGroup;
  serviceData;

  constructor (
    formBuilder: FormBuilder;
  )

  ngOnInit(): void {
    // get your service data here. We'll assume it's available

    this.form = this.formBuilder.group({
      controlName1 : new FormControl(''),
      controlName2 : new FormControl(''),
    });

    // every time the input value changes, get the associated values
    this.control1Subscription = this.form.get('controlName1').valueChanges.subscribe(value => {
        const data = this.serviceData.find(data => data.ctrlname === 'controlName1');
        this.data['controlName1'].value = value;
        this.data['controlName1'].type = data.type;
        this.data['controlName1'].unit = data.unit;
    });
  }

  ngOnDestroy(): void {
    this.control1Subscription.unsubscribe();
  }

}

You could create these input value changes subscriptions in a loop, substituting the hard-coded ctrlname values for the values in your data, making it scale to suit your needs.

Later, when you need to look up each set of values because you're able to reference each object by key, it's constant-time lookup and therefore as fast as you can retrieve them.