首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >动态选择角材料2版本6中下拉列表中的一些选项

动态选择角材料2版本6中下拉列表中的一些选项
EN

Stack Overflow用户
提问于 2018-05-25 23:21:55
回答 1查看 2.3K关注 0票数 0

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

myForm.html

代码语言:javascript
复制
  <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>

由于数据是由可观察到的传递的,所以我有这样的方法来捕获db中的skill_id数组:

代码语言:javascript
复制
this.skill_ids = data.skill_id_array; // [1, 3, 7]

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

代码语言:javascript
复制
//  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]); 
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-28 18:50:21

我不是英雄,在写了太多代码后,我无意中找到了解决方案。当data.skill_id_array行加载到编辑表单时,它将在下拉列表中显示先前选中的选项。一个非常简单的解决方案,与我最初的目标相比。

代码语言:javascript
复制
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);

我为那些想要看到解决方案的人在上下文中完整的编辑表单。

代码语言:javascript
复制
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.');
  }
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50537923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档