Home > other >  Incorrect binding type of the reactive control
Incorrect binding type of the reactive control

Time:09-13

I have a strange problem with one of my reactive control function (below). It seems to be bound to a type UserFunction instead of just string as initialized in *ngFor section of my template. If I execute this.form.get('function').value it returns UserFunction object - I would expect the string?

UserFunction definition:

export class UserFunction {
    id: string;
    userFunction: string;
}

Component:

userFunctions: UserFunction[] = [];
this.form = this.formBuilder.group({
                scheduledDate: ['', Validators.required],
                function: ['', [Validators.required, this.functionValidator]],
                required: [''],
                userAvailability: [''],
              });
              
        

HTML template:

    <select formControlName="function"  [ngClass]="{ 'is-invalid': submitted && f.function.errors }">

               
                <option *ngFor="let item of userFunctions" [value]='item'>
                    {{ item.userFunction }}
                </option>
            </select>
        

Sorry I can't explain that simpler then that.

CodePudding user response:

You need to bind the value for options correctly. Change your HTML as follows,

        <select formControlName="function"  [ngClass]="{ 'is-invalid': submitted && f.function.errors }">
            <option *ngFor="let item of userFunctions" [value]='item.userFunction'>
                {{ item.userFunction }}
            </option>
        </select>

Note that the value is now

[value]='item.userFunction'
  • Related