我的员工属于一个或多个团队。 我希望能够在下拉列表中选择多个员工,或者打开一个对话框,从中选择一个或多个团队。当我选择一些团队并单击“确定”时,我会搜索属于该团队的员工并将其添加到 formGroup 元素“chosenEmployees”中。 selectedEmployees 的值正确更改,但未更新下拉框中选中的值。 当我先选择一名员工然后打开团队对话框时,它会更新下拉框中选中的值。
<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();
}
});}}
我尝试过的东西
答案 0 :(得分:1)
我觉得问题是this.chosenEmployees的值一开始是null,你可以试试,在开始流程之前使用
this.chosenEmployees=this.chosenEmployees || []
确保以数组开头。
顺便说一句,您可以使用 spread operator 来连接两个数组
//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)]
})