angular - FormControl ValueChanges 管道未触发
问题描述
input
如果组件有值,我需要更新组件。这样做时,我正在设置通常通过将文本插入input
并从 中选择列表值来设置的值autocomplete
。即使我将 an 设置object
为FormControl
变量,valueChanges
管道也不会那样看。但我确信它formControl
得到了值,因为在前端我显示数据,formControl.value ? formControl.value.Name : ''
并且在我的情况下,表单控件的输入中有一个合法的名称。
这就是我显示数据的方式;
<div class="col-6" *ngIf="departmentUserList.length > 0">
<mat-form-field class="full-width">
<input type="text" placeholder="User" matInput [formControl]="departmentUserControl"
[matAutocomplete]="userAutoComplete"
[value]="departmentUserControl.value ? departmentUserControl.value.Name : ''">
<mat-autocomplete #userAutoComplete="matAutocomplete"
(optionSelected)="valueChange('SolvingUser', $event)">
<mat-option *ngFor="let user of filteredUserList | async" [value]="user">
{{user.Name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
这是我valueChanges
放入的管道ngOninit
;
this.filteredUserList = this.departmentUserControl.valueChanges.pipe(
startWith(''),
map(value => {
console.log("ToFilterValue =>>", value); // this is always '', from the startWith and does not change until I choose from the matAutoComplete
return typeof value === 'string' ? this.filterUser(value) : this.filterUser(value ? value.Name : '')
})
);
如果有值,这就是我更新值的方式;(这个函数在 valueChanges 管道声明之前在 ngOnInit 内部被调用)
mapObjects(){
// does not fire the valuechanges
this.departmentUserControl.setValue(this.bar.SolvingUser);
}
这是我的代码的一个小示例; StackBlitz
我在这里做错了什么?
解决方案
你有2个问题。
您必须添加
subscribe()
到valueChanges
.你必须在
this.mapObjects()
之后打电话valueChanges
。
this.filteredUserList = this.departmentUserControl.valueChanges.pipe(
startWith(""),
map(value => {
console.log("ToFilterValue =>>", value);
return typeof value === "string"
? this.filterUser(value)
: this.filterUser(value ? value.Name : "");
})
).subscribe();
this.mapObjects();
推荐阅读
- javascript - React - 使用 usestate 钩子推送数组
- python - 获取将值添加到列表中的所有可能结果
- mysql - 更新到 8.0.22 后 MySQL 服务器 InnoDB posix_fallocate() 错误
- c# - 从 SAP 将字符串转换为图像
- python - Powershell 显示“ObjectNotFound”
- typescript - 为什么服务构造函数在 Nest.js 控制器中没有 new 的情况下工作
- django - 如何保存用户模型“id”自动
- javascript - 更改任何选择框时启用按钮
- gradle - 未找到gradle注释处理器'org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor'
- java - 如何在将 String 转换为 LocalDateTime 时摆脱 StringIndexOutOfBoundsException