如何用反应式设置角料切屑控制 [英] How to setup Angular Material Chip Contol with reactive forms
本文介绍了如何用反应式设置角料切屑控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我与角材料有角反应式
对于我的所有控件,我添加了所需的验证器。
我不确定如何使用反应式表单正确设置芯片控件。
在哪里设置formControlName以便触发所需的验证器?目前我在输入字段上设置了它,我猜是错误的。我只希望CourseIds是带有课程ID的逗号分隔字符串。
TS:
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
name: new FormControl("", [Validators.required]),
courseIds: new FormControl("", Validators.required)
});
}
HTML:
<form [formGroup]="form" (ngSubmit)="submit()">
<mat-form-field>
<input matInput type="text" formControlName="name" placeholder="Name">
</mat-form-field>
<mat-form-field>
<mat-chip-list #chipList>
<mat-chip *ngFor="let cid of courseIds" (removed) = "...">
{{cid}}
</mat-chip>
<input matInput formControlName="courseIds"
[matChipInputFor]="chipList"
placeholder="Ids"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
</mat-form-field>
....
<button type="submit">OK</button>
</form>
推荐答案
尝试在<mat-chip-list>
级别设置formControlName
。
在模板中,将ngFor
设置为在courseIds
控件值上循环
<mat-form-field>
<mat-chip-list #chipList formControlName="courseIds">
<mat-chip *ngFor="let cid of form.get('courseIds').value" (removed) = "...">
{{cid}}
</mat-chip>
<input matInput
[matChipInputFor]="chipList"
placeholder="Ids"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
</mat-form-field>
然后在您的组件中,使用courseIds
的初始值创建表单组(如果有),否则使用空数组[]
(因为芯片显示的是数组而不是字符串)。在add()
和remove()
函数中,分别从courseIds
控件值中添加和删除值。
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
name: new FormControl("", [Validators.required]),
courseIds: new FormControl([], Validators.required)
});
}
add() {
...
// Add new input to courseIds control value
this.courseIds.value.push(value);
this.courseIds.updateValueAndValidity();
}
remove() {
...
// Remove element from control value array
this.courseIds.value.splice(index, 1); // where index = index of removed element
this.courseIds.updateValueAndValidity();
}
// use getter method to access courseIds control value easily
get courseIds() {
return this.form.get('courseIds');
}
这篇关于如何用反应式设置角料切屑控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文