menu

Questions & Answers

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>
Comments:
2023-01-18 17:42:02
The way you are using the FormBuilder is deprecated angular.io/api/forms/FormBuilder#group
Answers(2) :

Are you sure that your this.data.scannerObject.scannerName returns string?

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) {}
Comments:
2023-01-18 17:42:02
Indeed, passing the argument as an object only works with { value: this.data.scannerObject.scannerName, disabled: true } otherwise I had to put the value alone
2023-01-18 17:42:02
So you want to an object to the form?
2023-01-18 17:42:02
No, I was just saying that to use the disabled property you still need to use the deprecated API and it works but for only passing a default value the deprecated API does not work.