如何在angular2中设置动态创建表单的选择元素的值 [英] How to set the select element's value of a dynamically created form in angular2

查看:77
本文介绍了如何在angular2中设置动态创建表单的选择元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在同时处理两个问题.幸运的是,我已经缩小了范围,因此我可能会用一个plnkr示例来问一个问题.

I'm working on two problems at once. Fortunately, I've narrowed them down so I can probably ask about the in one question with one plnkr example.

这是我正在使用的plnkr代码: http://plnkr.co/edit/qv1BX7WtpYhw5B92SuoC?p =预览

Here's the plnkr code I'm working on: http://plnkr.co/edit/qv1BX7WtpYhw5B92SuoC?p=preview

这是什么?它显示了两张卡,最上面的卡是使用动态芯片的示例.

What is it? It shows two cards, the top card is an example of using Dynamic Chips.

这是怎么回事?删除第二块芯片后,该芯片的信息将显示在选择框中.

What's wrong with it? After the second chip is removed, that chip's information appears on the select box.

发生了什么事??在查看控制台输出时,我记录了select的值(< FormArray> this.updateProfileForm.controls ["personNames"].value ).它显示的是,在进行第一次选择时,该值为空白.第二次选择一个值时,该值将成为第一个选择的值.

What's happening? When looking at the console output, I've logged the select's value (<FormArray>this.updateProfileForm.controls["personNames"].value). What it shows is that when the first select is made, the value is blank. The second time a value is selected, the value becomes what the first selection is.

取出芯片后,我们看到该值仍然是先前选择的值.

After removing a chip, we see that the value is still that previously selected value.

我要做什么?我正在尝试将选择的值设置为空白.而且我还没有发现或找到设置值的方法.如果我尝试< FormArray> this.updateProfileForm.controls ["personNames"].value =''; ,它告诉我这对于仅具有吸气剂的属性是不可能的.

What am I trying to do? I'm trying to set the select's value to blank. And I have not discovered or found the way to set the value. If I try <FormArray>this.updateProfileForm.controls["personNames"].value = '';, it tells me this is not possible with a property that only has a getter.

将值设置为空白的正确方法是什么?

-代码块-

<!-- app.component.html -->
<form [formGroup]="updateProfileForm" novalidate (ngSubmit)="save(myForm)">
  <div id="names">
    <md-card>
      <md-toolbar color="primary">Dynamic Chips</md-toolbar>
        <md-card-content>
          <md-chip-list>
            <md-chip *ngFor="let person of people" (click)="removePerson($event)">{{person.name}} [X]</md-chip>
            <md-select id="names"
                       placeholder="Names"
                       formControlName="personNames"
                       (ngModelChange)="addPerson($event)">
                <md-option *ngFor="let name of names" value="{{name.code}}">
                    {{ name.name }}
                </md-option>
                <md-option disabled></md-option>
              </md-select>
          </md-chip-list>
      </md-card-content>
    </md-card>
  </div>
</form> 

-

// app.component.ts
  updateProfileForm: FormGroup;

   names = [
    {code: "F", name: "Frank"},
    {code: "G", name: "George"},
    {code: "H", name: "Henry"},
    {code: "I", name: "Inigo"},
    {code: "J", name: "Jose"},
    {code: "K", name: "Kevin"}
  ];

  removedNames = [];

  people: Person[] = [];

  constructor(private formBuilder: FormBuilder) {      
      this.updateProfileForm = this.formBuilder.group({
        personNames: ['', []]
      });
  }

  addPerson(selection): void {
    let selected = this.names.find(el => el.code === selection);

    this.people.push({name: selected.name});

    this.removedNames.push(selected);
    this.names.splice(this.names.findIndex(el => el === selected), 1);

    const control = <FormArray>this.updateProfileForm.controls["personNames"]
    console.log("Adding: control.value = ", control.value);

  }

  removePerson(chip) {
    // get name and remove the extra text
    let name = chip.target.innerText;
    name = name.substring(0, name.lastIndexOf(' '));

    // get the index of the name from the people array, then remove it from people (chips)
    let index = this.people.findIndex(el => el.name === name);
    this.people.splice(index, 1);

    // get the custom object from the removedNames array 
    let removedName = this.removedNames.find(el => el.name === name)
    // ... and add it back to names and sort
    this.names.push(removedName);
    this.names.sort(function(a, b) {
      if (a.name < b.name) return -1;
      if (a.name > b.name) return 1;
      return 0;
    });

    // ... and remove it from removedNames
    this.removedNames.splice(this.removedNames.findIndex(el => el.name === name), 1);

    const control = <FormArray>this.updateProfileForm.controls["personNames"]
    console.log("Adding: control.value = ", control.value);
  }

推荐答案

嗯,答案很简单.使用"patchValue": https://angular.io/docs/ts/latest/guide/reactive-forms.html#!#set-data

Hmm, the answer was really simple. Use "patchValue": https://angular.io/docs/ts/latest/guide/reactive-forms.html#!#set-data

对于上面的代码,我需要使用

For the code above, I need to use

this.updateProfileForm.patchValue({
    personNames: ''
});

在removePerson()方法的末尾.(也请删除最后两行- const control ... console.log

at the end of the removePerson() method. (Get rid of the last two lines, as well - const control... and console.log

这篇关于如何在angular2中设置动态创建表单的选择元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆