angular - 如何在角度 10 中使用 FromControl 初始化值 mat-selection-list
问题描述
我无法用 FormControl 的动态值初始化我的组件 Mat-Selection-List。
该表单似乎有效,但从未检查过我列表中的值。
///ts
ngOnInit(): void {
this.categoryService.getAllCategory()
.subscribe(data => {
this.cbxCategory = data;
},
error => console.log(error)
);
this.authService.getUser()
.subscribe(data => {
this.user = data;
},
error => console.log(error),
()=>this.initForm()
);
}
private initForm() {
this.editUserForm = this.formBuilder.group({
email: new FormControl(this.user.email, [Validators.required,Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$"),Validators.maxLength(50)]),
password: new FormControl(''),
passwordConfirm: new FormControl(''),
lstCat: new FormControl(this.user.lstCategory),
}, {
validator: MustMatch('password', 'passwordConfirm')
});
}
///html
<form [formGroup]="editUserForm" (ngSubmit)="onSave()" >
<table *ngIf="user">
...
<mat-selection-list formControlName="lstCat" class="col-md-12 col-sm-12">
<mat-list-option *ngFor="let cat of cbxCategory" [value]="cat">
{{cat.libelle}}
</mat-list-option>
...
</table>
</form>
解决方案
如果您使用的是 Angular 7+ 材质,请在 mat-selection-list 上使用compareWith输入属性,它将函数作为输入值。
此函数用于在确定哪些选项应显示为选中时将选项与所选值进行比较
组件.html
<form [formGroup]="clientForm">
<h1>
FormControl Value
</h1>
<pre>
{{ clientForm.get('myOtherControl').value | json }}
</pre>
<mat-selection-list *ngIf="listValue" formControlName="myOtherControl" [compareWith]="compare" >
<mat-list-option *ngFor="let list of listValue" [value]="list" multiple>{{list.name}}</mat-list-option>
</mat-selection-list>
</form>
组件.ts
compare(c1: {id: string}, c2: {id: string}) {
return c1?.id === c2?.id;
}
推荐阅读
- c# - 迁移的 asmx 服务需要什么样的项目
- gnu-screen - 无法通过记录到特定输出文件来启动 linux“屏幕”
- python - Pelican:通过从 YAML 读取元数据来自定义 index.html
- python - 如何在 Python 中处理套接字超时
- c - 如何使用相同的 UDP 套接字发送和接收数据包?我在这段代码中缺少什么?
- python - 在python中模拟一个类
- c# - 获取 InterpolatedStringExpressionSyntax 的值
- asp.net-core-2.1 - 没有配置 IAuthenticationSignInHandler 来处理方案的登录:Identity.Application
- sorting - 对具有 2 个值的子列表进行排序,其中 id 由最后带有连续数字的字符串组成
- c# - C# - 检查是否在 Windows10 上安装了 UWP 应用