简体   繁体   English

选择下拉值匹配以使其在预填充时不区分大小写

[英]select dropdown value matching to be case insensitive when prefilled

In Html template 在HTML模板中

<select [(ngModel)]="modelName">
  <option *ngFor="let ele of elements" [value]="element">{{ele}}</option>
</select>

In .ts file 在.ts文件中

this.elements = ['ABCd', 'mnOp'];
this.modelName = 'Abcd';

I Expect the value of the modelName 'ABCd' to be preselected from the list. 我希望从列表中预先选择modelName'ABCd'的值。

Currently nothing is displayed in the Select box though the modelName contains value 'Abcd' 当前,尽管modelName包含值“ Abcd”,但“选择”框中没有任何显示

The select's value is undefined because element is undefined so it is not able to match to the string 'Abcd' . select的值是undefined因为element是不确定的,因此它不能与字符串'Abcd'匹配。 To make the values lowcase I would map your element values to an object. 为了使值小写,我会将您的元素值映射到一个对象。

Should be: 应该:

<select [(ngModel)]="modelName">
    <option *ngFor="let ele of elements" [value]="ele.value">{{ele.label}}</option> 
</select>

In the component: 在组件中:

this.elements = ['ABCd', 'mnOp'].map((v) => ({ value: v.toLowerCase(), label: v }));

this.modelName = 'abcd';

Like teddy said, the strings compared between the 'select' value and the 'element' values are case-sensitive. 就像泰迪所说的那样,在“选择”值和“元素”值之间进行比较的字符串区分大小写。 You can either copy the value from the first element manually or, since you already conveniently have the array in your code, assign the first element of the array directly to your model. 您可以手动从第一个元素复制值,或者,由于您已经很方便地在代码中包含数组,因此可以将数组的第一个元素直接分配给模型。 This way if for some reason the array is created dynamically you won't have to worry about finding the value; 这样,如果由于某种原因而动态创建了数组,则不必担心寻找值。

HTML 的HTML

<select [(ngModel)]="modelName">
    <option *ngFor="let ele of elements" [value]="ele">{{ele}}</option> 
</select>

TS TS

this.elements = ['ABCd', 'mnOp'];
this.modelName = this.elements[0];

EDIT 编辑

Based on what you've said I believe the best solution for you is indeed to change the case of the variables. 根据您所说的,我相信最适合您的解决方案确实是更改变量的大小写。 Angular provides a couple pipes to do so. Angular提供了一些管道来做到这一点。 This method requires that you split the two-way binding up, and create two different fields for property binding and event binding . 此方法要求您拆分双向绑定 ,并为属性绑定事件绑定创建两个不同的字段。 See below: 见下文:

HTML 的HTML

<select 
    [ngModel]="modelName | uppercase"
    (change)="modelName = $event" >
    <option *ngFor="let ele of elements" [value]="ele | uppercase">
        {{ele}}
    </option> 
</select>

Hope this helps someone. 希望这对某人有帮助。 Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM