首页 > 解决方案 > 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 。但是有两个问题:

  1. 初始化组件时,选择中没有值,但 filter.sizes.width 的值为 0。我可以查看 Comment_01 下的字符串 {{filter.sizes.width}}
  2. 当 clearFilter() 方法更改 filter.sizes.width 时,选择中再次变为没有值。

我该如何解决?

标签: javascriptangulartypescriptselectbinding

解决方案


听起来您的 facet.sizes[0].parts.width 数组不包含值 === 0。我看到您的选项值为 null,但 null 不等于 0,因此不会被选中。如果您添加一个值为 === 0 的选项;它应该选择它。


推荐阅读