我正在处理两个问题。幸运的是,我缩小了它们的范围,所以我可以用一个plnkr例子来问一个问题。如何在angular2中设置select元素的动态创建表单的值
这里是plnkr代码我工作:http://plnkr.co/edit/qv1BX7WtpYhw5B92SuoC?p=preview
这是什么?它显示了两张牌,顶牌是使用动态筹码的一个例子。
它有什么问题?第二块芯片被移除后,该芯片的信息出现在选择框中。
发生了什么事?查看控制台输出时,我记录了选择的值(<FormArray>this.updateProfileForm.controls["personNames"].value
)。它显示的是当第一次选择时,值是空白的。第二次选择一个值时,该值将成为第一个选择的值。
删除芯片后,我们看到该值仍然是之前选定的值。
我想要做什么?我试图设置选择的值为空白。而且我还没有发现或找到设置价值的方法。如果我尝试<FormArray>this.updateProfileForm.controls["personNames"].value = '';
,它告诉我这对于只有吸气剂的属性是不可能的。
我应该用什么方法将值设置为空白?
- 代码块 -
<!-- 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);
}