我有一個設計,我通過從下拉列表中選擇一個項目,將一個芯片添加到我的頁面。我可以點擊它來移除芯片。但是,我似乎無法清除選擇元素的值。我嘗試了幾件事,但都沒有成功。如何清除選擇元素
採用了棱角分明材質選擇元素: https://plnkr.co/edit/KU1CxBqLwG5XtbvyEjJj?p=preview
採用了棱角分明的選擇元素: https://plnkr.co/edit/ewSlIRDHii3PnXRtnKgw?p=preview
HTML:
<div class="chips-overview-example">
<md-card>
<md-toolbar color="primary">Dynamic Chips</md-toolbar>
<md-card-content>
<md-chip-list>
<md-chip *ngFor="let person of people" (click)="remove($event)">
{{person.name}}
</md-chip>
<md-select id="names"
placeholder="Names"
[ngModel]="name"
(ngModelChange)="add($event)">
<md-option *ngFor="let name of names"
value="{{name.code}}">
{{name.name}}
</md-option>
</md-select>
</md-chip-list>
</md-card-content>
</md-card>
</div>
Component.ts
import {Component, ElementRef, Output} from '@angular/core';
export interface Person {
name: string;
}
@Component({
selector: 'chips-overview-example',
templateUrl: 'chips-overview-example.html',
styleUrls: ['chips-overview-example.css']
})
export class ChipsOverviewExample {
visible: boolean = true;
@Output() nameForm;
names = [
{code: "F",name: "Frank",description: ""},
{code: "G",name: "George",description: ""},
{code: "H",name: "Henry",description: ""},
{code: "I",name: "Inigo",description: ""},
{code: "J",name: "Jose",description: ""},
{code: "K",name: "Kevin",description: ""}
];
removedNames = [];
people: Person[] = [];
add(selection): void {
let selected = this.names.find(el => el.code === selection);
console.log("adding: ", selected, " to ", JSON.stringify(this.people));
this.people.push({name: selected.name});
this.removedNames.push(selected);
this.names.splice(this.names.findIndex(el => el === selected), 1);
}
remove(chip) {
let name = chip.target.innerText;
let index = this.people.findIndex(el => el.name === name);
this.people.splice(index, 1);
this.names.push(this.removedNames.find(el => el.name === name));
this.removedNames.splice(this.removedNames.findIndex(el => el.name === name), 1);
this.names.sort(function(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
}
toggleVisible(): void {
this.visible = false;
}
}
main.ts(模塊)
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MaterialModule} from '@angular/material';
import {ChipsOverviewExample} from './chips-overview-example';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
MaterialModule,
],
declarations: [ChipsOverviewExample],
bootstrap: [ChipsOverviewExample],
providers: []
})
export class PlunkerAppModule {}
platformBrowserDynamic().bootstrapModule(PlunkerAppModule);
清理ngModel:'this.name ='''? – developer033
這隻有一次,但第二次失敗。另外,我剛剛注意到,即使在我的add()方法中有條件,它也會添加芯片。 – Machtyn
如果您只是添加一個空值的選項,該怎麼辦? ' '在其他選項之前?當然後面'this.name =''' –
smnbbrv