Home > database >  Not able to set value of input field
Not able to set value of input field

Time:05-28

I am trying to check if an object has a value and does not throw an error. If so, pass it as the value of an input field.

export class DialogServiceTabletAddRowComponent implements OnInit {
  service?: string;

  constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComponent>, private _fb: FormBuilder, @Inject(MAT_DIALOG_DATA) public data: ServiceDataToDialog) {
    try {
      this.service = this.data[this.data.id].allServices[this.data.id][this.data.id].service;
    }
    catch (e) {
      this.service = '';
    }
    console.log(this.service);
    })

  }

  mainForm = this._fb.group({
    service: [this.service, Validators.required]
  })


}

console.log(this.service); gives me the correct value but the value of my input field is still empty. How comes?

CodePudding user response:

Put this.mainForm = this._fb.group... code in the constructor after the try/catch. Also add public mainForm: FormGroup as a class property

The issue here is how TypeScript handles initializing class properties. Under the hood it initializes them immediately inside the constructor

  • Related