【发布时间】:2020-09-08 06:54:25
【问题描述】:
让我们讨论一下代码概述, 我已经在多复选框 mat-select angular material 中绑定了学生姓名。我在默认情况下绑定了前三个学生在应用程序的初始加载时选中,因此我们可以看到学生的三个复选框默认选中。
应用程序还有另一个条件:从所有学生列表中,用户可以选择任何且仅三个学生,如果用户尝试选择三个以上的学生,我将显示警报消息“最多可以选择 3 个学生!”
<mat-form-field>
<mat-select placeholder="Select Student"
[formControl]="studentdropdownsControl" multiple>
<mat-option *ngFor="let student of studentdropdowns" [value]="student.value"
(click)="studentdropdown($event,student,studentdropdownsControl)">
{{student.value}}
</mat-option>
</mat-select>
</mat-form-field>
studentdropdownsControl = new FormControl();
selectedstudent =[];
studentdropdowns = [{value: "Rickey", id: 0},{value: "JohnSon", id: 1},{value: "Salmon", id: 2},{value: "vickey", id: 3},{value: "Jony", id: 4}, {value: "Rock/679", id: 5},{value: "Batista/641", id: 6},{value: "Sunny/859", id: 7},{value: "Eliza/1090", id: 8}]
ngOnit()
{
this.getstudentCallsdropdown();
}
public async getstudentCallsdropdown(): Promise<void> {
{
// Logic to bind by default three student checkbox in dropdown on intial loading
this.studentdropdownsControl = new FormControl([this.studentdropdowns[0].value, this.studentdropdowns[1].value, this.studentdropdowns[2].value]);
}
}
public studentdropdown(event: MatOptionSelectionChange, value: string, selectedstudent: any): void {
//selectedstudent is nothing but value of select and deselect checkbox.
this.selectedstudent = selectedstudent.id;
if (this.selectedstudent.length > 3) {
this.studentdropdownsControl = new FormControl([this.selectedstudent[0], this.selectedstudent[1],
this.selectedstudent[2]]);
alert("Maximum of 3 Studentcan be selected!");
}
}
现在让我们讨论上图中的问题,我正在尝试选择 vickey,是的,我无法选择。非常完美!,Condition(if (this.selectedstudent.length > 3)) 工作正常,但现在看下图
一旦我们点击确定窗口警报
我已经选择了三个学生,现在当我尝试选择 Salmon 时,我的条件(如果 (this.selectedstudent.length > 3)) 失败并且能够选择或标记对 Salmon 的检查,有趣的是它取消选择Vickey 自动。 因此,通过与其他学生核对,我观察到一件事“从上行(顶部)到下行(底部)我的状况运行良好,而下行(底部)到上行(顶部)则无法正常工作”。
为什么会发生这种情况缺少一些东西?或者它在数组中绑定元素的问题,或者是表单控件的奇怪行为。
【问题讨论】:
标签: angular checkbox angular-material form-control