【发布时间】:2026-01-22 23:05:01
【问题描述】:
我正在尝试使用“带形状控制的角材料芯片”,因为我需要知道选择了哪些芯片。我目前不知道如何在初始化时用 string[] 填充 FormControl- 和 Set-Constructor 。这是我的代码/类:
export class EventPlanningComponent implements OnInit {
allServices: ServiceDto[];
keywords = new Set(); // new Set(['name1', 'name2', ...])
formControl = new FormControl(); // new FormControl(['defaultName1', 'defaultName2', ...])
constructor(
private readonly serviceService: ServiceService
) { }
async ngOnInit(): Promise<void> {
await this.initServices();
}
async initServices(): Promise<void> {
this.allServices = await this.serviceService.getAllServices().toPromise();
for (const service of this.allServices) {
this.keywords.push(service.name); // this can´t work
if (service.default === true) {
this.formControl.push(service.name); // this too
}
}
}
removeKeyword(keyword: string) {
this.keywords.delete(keyword);
}
}
谢谢
编辑:我想实现可以从一系列芯片中选择多个芯片,默认选择一些......
这是我的模板:
<mat-form-field class="chip-list" appearance="fill">
<mat-label>Dienste auswählen</mat-label>
<mat-chip-list #chipList aria-label="Dienste auswählen" multiple [formControl]="formControl">
<mat-chip *ngFor="let keyword of keywords" [selected]="false" [value]="keyword">
{{keyword}}
</mat-chip>
</mat-chip-list>
</mat-form-field>
<p>
<b>The following keywords are selected:</b> {{formControl.value}}
</p>
【问题讨论】:
-
你到底想要达到什么目的?
-
您的模板中有
mat-form-fieldinput控件吗?为什么要创建FormControls 的数组?你能展示你的模板吗? -
this.keywords.push(service.name);变成 this.keywords.add(service.name);我发现了