在Angular Material 2 Version 6的下拉列表中动态选择一些选项

时间:2018-05-25 23:21:56

标签: angular-material2

我有一个用于编辑用户个人资料的表单。在它是技能复选框的下拉列表,多选。我从配置文件数据对象中的db获取先前选择的选项/技能数组[1,3,7],并且我想在编辑配置文件表单中显示这些技能。当用户编辑他们的个人资料时,他们可以看到他们之前选择的内容。

myForm.html

  <li><label class="label-pad">Select main skills: </label>
    <mat-form-field>
      <mat-select  placeholder="Select your skills" type="text" id="skillIds"
                   formControlName="skill_id_array" required multiple>
        <mat-option *ngFor="let skill of skills"
                    [value]="skill.skill_id">{{skill.skill_name}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </li>

当数据由observable传递时,我有这个用于捕获db中的skill_id数组:

this.skill_ids = data.skill_id_array; // [1, 3, 7]

在下拉列表实例化后,我需要遍历this.skill_ids并以某种方式检查下拉列表中的相关框。也许这是一个开始,但我现在迷失了。有什么想法吗?

//  Check the previously selected option boxes in the skills dropdown list.

private checkSelectedOptions(skill_ids) {
  console.log('skill array', skill_ids);  // [1, 3, 7]

  // Need to loop through the array and match id's with names and check the proper checkboxes.

  for (let i = 0; i < skill_ids.length; i++) {
  console.log('skill_ids: ', skill_ids[i]); 
  }
}

1 个答案:

答案 0 :(得分:0)

I'm no hero, I stumbled into the solution after writing too much code. The data.skill_id_array line will display the previously checked selected options in the dropdown list when it loads into the edit form. A very simple solution compared to where I was originally going with this.

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);

My complete edit form for those who want to see the solution in context.

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.');
  }
}