Home > Enterprise >  how can i set a value for property
how can i set a value for property

Time:03-13

I am working on an Angular application using the reactive form. I get the value of the fields using the form group but those fields are created dynamically (the user controls the number of rows of fields). so for that, I have done the following code :

this.formSaisieSecondary = this.fb.group({
  options:this.fb.array([])
});

newOption(): FormGroup {  
return this.fb.group({  
  date:['', Validators.required],

  cargoA:['', Validators.required],
  cargoB:['', Validators.required],
  cargoC:['', Validators.required],
  cargoD:['', Validators.required],
  cargoE:['', Validators.required],

  unite:[this.unite, Validators.required],

  siloA:['silo1', Validators.required],
  siloB:['silo2', Validators.required],
  siloC:['silo3', Validators.required],
  siloD:['silo4', Validators.required],
  siloE:['silo5', Validators.required],

  comment:[''] 
})  
}

options() : FormArray {  
   return this.formSaisie.get("options") as FormArray ;
}
 
AddOption(){ 
   this.options().push(this.newOption()); 
}

the HTML code :

<form [formGroup]="formSaisie">
        <div formArrayName="options">
            <div  style="height: 23px;" *ngFor="let option of options().controls; let i = index" [formGroupName]="i">
                <div >
                    <input formControlName="date" type="text" formControlName="date" hidden [(ngModel)]="listDate[i]">
                    <p>{{listDate[i]}}</p>
                </div>
                <div >
                    <mat-form-field  appearance="fill">
                        <mat-label>Cargaison</mat-label>
                        <mat-select formControlName = "cargoA" required>
                            <mat-option *ngFor="let cargo of dataEx" [value]="cargo.cargoId">
                                {{cargo.vessel  " "  cargo.externalId}}
                            </mat-option>
                        </mat-select>
                    </mat-form-field>
                </div>
 .............

the code is inspired by the following the enter method

my question here is how I can get or set a value for a property(field) for example for getting a value I can do :

let value = this.formSaisie.value.options[0];
value.cargoA;

but I can't set a value for afield.

CodePudding user response:

this.options().at(0).get('cargoA').setValue(someValue)

This sets the cargoA property of the group at index 0 in the form array to someValue

Side note: strongly recommend to not use ngModel and reactive forms in the same form. They will conflict with each other and be unpredictable at times.

CodePudding user response:

You can do it by for example this.formSaisie.get('cargoA').setValue(someValueYouWouldLikeToSet)

edit: So do it like: this.formSaisie.get('options').get('cargoA').setValue(someValue) - should work

  • Related