Home > database >  Why my FormControl displays [object Object]?
Why my FormControl displays [object Object]?

Time:01-17

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 >
    <div >
      <div >
        <mat-form-field  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>

CodePudding user response:

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

CodePudding user response:

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) {}
  • Related