angularangular-formsangular-formbuilder

Why my FormControl displays [object Object]?


The form control has a default value coming from Component data which is displayed fine when disabled.
But when the field is enabled I get [object Object] in the input field.

It's almost the same to other components that work well in the project so I fail to see what I did wrong here.

ngOnInit(): void {
    this.form = this.fb.group({
      scannerName: [
        { value: this.data.scannerObject.scannerName /* , disabled: true */ },
        [ Validators.required ],
      ]
    });
}
<form [formGroup]="form" (submit)="save$.next($event)">
  <mat-dialog-content class="mat-typography">
    <div class="content">
      <div class="d-flex">
        <mat-form-field class="m-1" appearance="outline" formErrors="scannerName">
          <mat-label>Name</mat-label>
          <input matInput type="string" name="scannerName" formControlName="scannerName" aria-label="scanner-name" />
          <mat-error formError="required" when="touched">Required</mat-error>
        </mat-form-field>
      </div>
    </div>
  </mat-dialog-content>
  <mat-dialog-actions align="end">
    <button type="button" mat-dialog-close>Cancel</button>
    <button type="submit">Save</button>
  </mat-dialog-actions>
</form>

Solution

  • In my opinion, you are using the group from FormBuilder the wrong way

    Try to execute following ngOnInit method:

    ngOnInit(): void {
        this.form = this.fb.group({
          scannerName: [this.data.scannerObject.scannerName, [Validators.required]]
    });
    

    Also note that you should have imported the ReactiveFormsModule from @angular/forms.

    The form builder should be injected in the component like following:

    constructor(private fb: FormBuilder) {}