[英]Trigger [compareWith] programmatically in mat-select/mat-option
我的员工属于一个或多个团队。 我希望能够在下拉列表中选择多个员工,或者打开一个对话框,从中选择一个或多个团队。 当我选择一些团队并单击“确定”时,我会搜索属于该团队的员工并将其添加到 formGroup 元素“chosenEmployees”中。 selectedEmployees 的值正确更改,但未更新下拉框中选中的值。 当我首先选择一名员工然后打开 Teams-Dialog 时,它会更新下拉框中的选中值。
<form [formGroup]="formGroup" *ngIf="this.formGroup">
<div>
<mat-form-field>
<mat-label>{{ 'numbers' | translate }}</mat-label>
<mat-select formControlName="chosenEmployees" [compareWith]="compareChosenEmployees" (selectionChange)="updateEmployees(chosenEmployees)" multiple disableOptionCentering>
<mat-option *ngFor="let employee of allEmployees" [value]="employee">
{{ employee.employeeId + '(' + employee.teamId + ')'}}
</mat-option>
</mat-select>
</mat-form-field>
<span fxFlex="5"></span>
<button mat-button type="submit" color="primary" (click)="addTeam()">
<mat-icon>add</mat-icon>
<mat-label>{{ 'teams.add' | translate }}</mat-label>
</button>
</div>
</form>
在 .ts 中,它看起来像这样: selectedEmployee 变量:
public chosenEmployees: Employee[] = [];
我在 ngOnInit 函数中的 FormGroup:
const formFields = {
endDate: new FormControl(undefined),
hasEnddate: new FormControl(true),
chosenEmployees: [this.chosenEmployees]
};
this.formGroup = this.formBuilder.group(formFields);
我的 addTeam 功能:
addTeam(){
const dialogRef = this.dialog.open(AddTeamDialogComponent, {
data:
[
this.chosenTeams,
this.allTeams
]
});
dialogRef.afterClosed().subscribe((addTeamResult: AddTeamResult) => {
this.changeDetectorRef.markForCheck();
if (addTeamResult){
this.chosenTeams = addTeamResult.teams;
if (addTeamResult.teams !== undefined){
addTeamResult.teams.forEach(team => {
const employees =
this.allEmployees.filter(emp => emp.teamId === team.id);
employees.forEach(e => {
if (this.chosenEmployees.length === 0){
this.chosenEmployees.push(e);
}
else if (!(this.chosenEmployees.find(_ => _.employeeId === e.employeeId && _.teamId === team.id))){
this.chosenEmployees.push(e);
}
});
});
}
this.formGroup.controls.chosenEmployees.setValue(this.chosenEmployees);
// this.formGroup.controls["chosenEmployees"].patchValue(this.chosenEmployees);
// this.formGroup.patchValue({chosenEmployees: this.chosenEmployees});
this.updateEmployees(this.chosenEmployees);
this.changeDetectorRef.detectChanges();
}
});}}
我尝试过的事情
我觉得问题是this.chosenEmployees的值一开始是null,你可以试试,在开始流程之前使用
this.chosenEmployees=this.chosenEmployees || []
确保以数组开头。
顺便说一句,您可以使用扩展运算符来连接两个数组
//really I don't know what is your chosenEmployees
//I imagine that should be
//this.chosenEmployees=this.form.value.chosenEmployes || []
//but I don't know
this.chosenEmployees=this.chosenEmployees || []
addTeamResult.teams.forEach(team => {
this.chosenEmployees=[...this.chosenEmployees,
...this.allEmployees.filter(emp => emp.teamId === team.id)]
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.