mdziob mdziob - 1 month ago 11
Javascript Question

Angular2 reactive form default input value

I've got following code that initialize form in my component:

let editMode: boolean = !!this.template.templateId;

this.editTemplateForm = this.formBuilder.group({
templateId: {value: editMode ? this.template.templateId : '', validators: [Validators.required, this.templateIdValidator]},
dataStorageTime: {value: editMode ? this.template.dataStorageTime : this.globalParameter.dataStorageTime, Validators.required, Validators.pattern("[0-9]+")]});


Value of variable
this.template.templateId
is undefined, so
editMode
is false. For
dataStorageTime
correct default value is set in linked input in form. Hovewer, for templateId input is set to "[object Object]" instead of empty string.

I'm using angular2 final realease.

Answer

This is the solution to my problem:

this.editTemplateForm = this.formBuilder.group({
templateId: [editMode ? this.template.templateId : '', [Validators.required, this.templateIdValidator]],
dataStorageTime: [editMode ? this.template.dataStorageTime : this.globalParameter.dataStorageTime, [Validators.required, Validators.pattern("[0-9]+")]]
});
Comments