Я не герой, я наткнулся на решение после написания слишком большого количества кода.Строка data.skill_id_array отобразит предварительно выбранные выбранные параметры в раскрывающемся списке при загрузке в форму редактирования.Очень простое решение по сравнению с тем, к чему я изначально стремился.
this.httpService.getRecordById(this.dbTable, this.recordId)
.subscribe(data => {
data.skill_id_array = data.skill_id_array.map(Number); // Displays previously checked boxes in edit view.
this.fillForm(data);
Моя полная форма редактирования для тех, кто хочет увидеть решение в контексте.
import { Component, AfterViewInit, Inject, ViewChild, ViewEncapsulation } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Subscription } from 'rxjs';
import { HttpService } from '../../services/http.service';
import { MemberModel } from '../member.model';
import { AddEditFormComponent } from '../add-edit-form/add-edit-form.component';
import { EditProcessorService } from '../../services/processors/edit-processor.service';
import { MessagesService } from '../../services/messages-service/messages.service';
import { FormErrorsService } from '../../services/form-validation/form-errors.service';
@Component({
selector: 'app-edit-member',
templateUrl: './edit-member.component.html',
encapsulation: ViewEncapsulation.None
})
export class EditMemberComponent implements AfterViewInit {
private dbTable = 'members';
private formValue: MemberModel;
private skill_ids;
private recordId: number;
private dbColumn;
private paginator;
private dataSource;
private subscription: Subscription; // For ngOnDestroy.
// This is a form group from FormBuilder.
@ViewChild(AddEditFormComponent) private addEditForm: AddEditFormComponent;
constructor(
private httpService: HttpService,
@Inject(MAT_DIALOG_DATA) public data: any,
public dialogRef: MatDialogRef<EditMemberComponent>, // Used in modal for close()
private messagesService: MessagesService,
public formErrorsService: FormErrorsService,
private editProcessorService: EditProcessorService,
) {}
// ---- GET DATA BY ID ----
// Need to load the data after the form is rendered so ngOnInit didn't work.
// setTimeout is a hack to avoid ExpressionChangedAfterItHasBeenCheckedError
ngAfterViewInit() {
setTimeout(() => {
this.fetchRecord();
}, 200);
}
public fetchRecord() {
this.recordId = this.data.recordId;
this.dbColumn = this.data.dbColumn;
this.paginator = this.data.paginator;
this.dataSource = this.data.dataSource;
// Display the data retrieved from the data model to the form model.
this.httpService.getRecordById(this.dbTable, this.recordId)
.subscribe(data => {
data.skill_id_array = data.skill_id_array.map(Number); // Displays previously checked boxes in edit view.
this.fillForm(data);
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.message);
this.handleError(err);
});
}
// Populate the form, called above in fetchRecord().
private fillForm(parsedData) {
this.addEditForm.addEditMemberForm.setValue({
first_name: parsedData.first_name,
middle_initial: parsedData.middle_initial,
last_name: parsedData.last_name,
skill_id_array: parsedData.skill_id_array,
...
});
}
// ---- UPDATE ---- Called from edit-member.component.html
public update() {
// right before we submit our form to the server we check if the form is valid
// if not, we pass the form to the validateform function again. Now with check dirty false
// this means we check every form field independent of whether it's touched.
// https://hackernoon.com/validating-reactive-forms-with-default-and-custom-form-field-validators-in-angular-5586dc51c4ae.
if (this.addEditForm.addEditMemberForm.valid) {
this.formValue = this.addEditForm.addEditMemberForm.value;
this.httpService.updateRecord(this.dbTable, this.recordId, this.formValue)
.subscribe(
result => {
// Update the table data view for the changes.
this.editProcessorService.updateDataTable(result, this.recordId, this.dbColumn, this.paginator, this.dataSource);
this.success();
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.message);
this.handleError(err);
}
);
} else {
this.addEditForm.formErrors = this.formErrorsService.validateForm(
this.addEditForm.addEditMemberForm,
this.addEditForm.formErrors, false
);
}
this.reset();
}
// ---- UTILITIES ----
private reset() {
this.addEditForm.addEditMemberForm.reset();
}
private success() {
this.messagesService.openDialog('Success', 'Database updated as you wished!');
}
private handleError(error) {
this.messagesService.openDialog('Error em1', 'Please check your Internet connection.');
}
}