javascript - ngModel更改时如何解决select中没有值?
问题描述
一个项目包含一个组件和一个服务。
组件注入服务并使用服务字段过滤器。在组件 hmtl 中有一个选择。select 的 [(ngModel)] 绑定到 filter.sizes.width。
组件:
@Component({
selector: 'app-facet-sizes-static',
templateUrl: './facet-sizes-static.component.html',
styleUrls: ['./facet-sizes-static.component.scss']
})
export class FacetSizesStaticComponent implements OnInit {
constructor(
private Search: SearchService
) {
this.filter = Search.filter;
}
clearFilter() {
this.filter.sizes.width = 0;
}
}
它的模板:
<div (click)="clearFilter()"></div>
<!-- Comment_01 -->
{{filter.sizes.width}}
<div *ngIf="filter.sizes">
<select name="width"
[(ngModel)]="filter.sizes.width">
<option [ngValue]="null">~</option>
<option *ngFor="let item of facet.sizes[0].parts.width; let x = index"
[ngValue]=item>
{{ item }}
</option>
</select>
</div>
服务:
export class SearchService {
filter: SearchServiceFilter = null;
constructor() {
this.filter = {
sizes: {
width: 0
},
};
}
}
当我在 select 中更改选项时,它会更改 filter.sizes.width 。但是有两个问题:
- 初始化组件时,选择中没有值,但 filter.sizes.width 的值为 0。我可以查看 Comment_01 下的字符串 {{filter.sizes.width}}
- 当 clearFilter() 方法更改 filter.sizes.width 时,选择中再次变为没有值。
我该如何解决?
解决方案
听起来您的 facet.sizes[0].parts.width 数组不包含值 === 0。我看到您的选项值为 null,但 null 不等于 0,因此不会被选中。如果您添加一个值为 === 0 的选项;它应该选择它。
推荐阅读
- c - 使用 malloc 函数时出现“分段错误(核心转储)”错误
- php - 有没有办法在 php 变量中回显?
- c# - C# WPF 数据网格显示错误:正在显示的对象
- python - 无法检查 Postgres DB aiohttp 中是否存在用户
- reactjs - react组件如何在没有mapStateToProps的情况下获取数据
- python - 我正在尝试使用 python 获取 sqlite 并希望能够获得满足特定条件的行数
- mongodb - MongoDB动态子字段名称
- python - Docker:无法从 dockerfile 安装 Python 库,尽管可以从容器的 shell 中手动安装它们
- python - 向 pandas DataFrame wint 索引名称和列名称添加单个值
- java - 我无法在 recyclerview 中使用 sqlite 显示新添加的数据