Home > other >  can not assign a value to a angular formcontrol
can not assign a value to a angular formcontrol

Time:12-29

so, I am trying to assign a value to a formcontrol in ts, but it displays blanks in html.. :(

here is the TS:

constructor(private readonly messageToastService: NxMessageToastService,
          private route: ActivatedRoute, private router:Router,
          private appSettingsService: AppSettingsService)
{ 
  this.initialSettingsForm = new FormArray([this.createInitialSettingsFormGroup()]);      
  this.initialSettingsForm.get('connectionString')?.setValue('testConnectionString')          
}

inside the 'createInitialSettingsFormGroup' i just create the form and adding the formcontrols:

private createInitialSettingsFormGroup() {
return new FormGroup({
  connectionString: new FormControl('', Validators.required),

and on HTML part I have:

<ng-container *ngFor="let control of initialSettingsForm.controls; index as i"
                    [formGroup]="getInitialSettingsFormGroup(i)">
                    <fieldset >
                        <div nxRow>
                            <!-- connection string -->
                            <div nxCol="12, 12, 12, 10, 8" nxColOffset="0, 0, 0, 1, 2">
                                <nx-formfield nxLabel="Db Connection String:">
                                    <input nxInput formControlName="connectionString" type="string"
                                        autocomplete="off" />
                                    <nx-error *ngIf="control.get('connectionString')?.errors?.['required']"
                                        nxFormfieldError>
                                        This field is required!
                                    </nx-error>
                                    <nx-icon nxFormfieldAppendix name="info"
                                        [nxPopoverTriggerFor]="popoverDbConnection" nxPopoverTrigger="hover">
                                    </nx-icon>
                                </nx-formfield>
                            </div>
                        </div>

'getInitialSettingsFormGroup':

  getInitialSettingsFormGroup(index: number): FormGroup {
return this.initialSettingsForm.controls[index] as FormGroup;

}

I know that i can set up the default value for a formcontrol when I create it, but i need to set up the value later on when the data comes from the settingsService..

right now i don't understand why i can set up the default value when i create the formControl but it does not work when I am trying to set up the value for that control later on.. Thanks for the help and suggestions!

CodePudding user response:

Seems like you have to access the index 0 at first here

this.initialSettingsForm.get('connectionString')?.setValue('testConnectionString')

Like

this.initialSettingsForm.at(0).get('connectionString')?.setValue('testConnectionString')
  • Related