简体   繁体   English

如何在angular2中设置动态创建表单的选择元素的值

[英]How to set the select element's value of a dynamically created form in angular2

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示例来询问一个问题。

Here's the plnkr code I'm working on: http://plnkr.co/edit/qv1BX7WtpYhw5B92SuoC?p=preview 这是我正在使用的plnkr代码: 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. 取出第二块芯片后,该芯片的信息将显示在选择框中。

What's happening? 发生了什么? When looking at the console output, I've logged the select's value ( <FormArray>this.updateProfileForm.controls["personNames"].value ). 当查看控制台输出时,我记录了select的值( <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. 取出芯片后,我们看到该值仍然是先前选择的值。

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 = ''; 如果我尝试<FormArray>this.updateProfileForm.controls["personNames"].value = ''; , it tells me this is not possible with a property that only has a getter. ,它告诉我这对于仅具有吸气剂的属性是不可能的。

What is the proper method I should use to set the value to blank? 将值设置为空白应该使用什么正确的方法?

-- Code block -- -代码块-

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

Hmm, the answer was really simple. 嗯,答案很简单。 Use "patchValue": https://angular.io/docs/ts/latest/guide/reactive-forms.html#!#set-data 使用“ 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: ''
});

at the end of the removePerson() method. 在removePerson()方法的末尾。 (Get rid of the last two lines, as well - const control... and console.log (也摆脱最后两行const control...console.log

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM