微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Angular2动态输入字段在输入更改时失去焦点

我正在制作一个动态的表格. Field有一个值列表.每个值都由一个字符串表示.

export class Field{
    name: string;
    values: string[] = [];
    fieldType: string;
    constructor(fieldType: string) {this.fieldType = fieldType;}
}

我的组件中有一个函数,它为字段添加一个新值.

addValue(field){
    field.values.push("");
}

值和按钮在我的HTML中显示如下.

<div id="dropdown-values" *ngFor="let value of field.values; let j=index">
    <input type="text" class="form-control" [(ngModel)]="field.values[j]" [name]="'value' + j + '.' + i"/><br/>
</div>
<div class="text-center">
    <a href="javascript:void(0);" (click)="addValue(field)"><i class="fa fa-plus-circle" aria-hidden="true"></i></a>
</div>

只要在输入值中写入一些文本,输入就会失去焦点.
如果我向字段添加许多值,并且我在一个值输入中写入一个字符,则输入将失去焦点,并且字符将写入每个输入.

解决方法:

当数组是基本类型时,会发生这种情况,在您的情况下是String数组.这可以通过使用TrackBy来解决.因此,更改模板以匹配以下内容

<div *ngFor="let value of field.values; let i=index; trackBy:trackByFn">
    <input type="text" [(ngModel)]="field.values[i]"  /><br/>
</div>
<div>
    <button (click)="addValue(field)">Click</button>
</div>

并在ts文件添加函数trackByFn,它返回值的(唯一)索引:

trackByFn(index: any, item: any) {
   return index;
}

这是一个关于同一问题的link,除了AngularJS的问题,但问题与你的问题相对应.最重要的摘录自该页面

You are repeating over an array and you are changing the items of the array (note that your items are strings, which are primitives in JS and thus compared “by value”). Since new items are detected, old elements are removed from the DOM and new ones are created (which obvIoUsly don’t get focus).

使用TrackBy Angular可以根据唯一标识符跟踪已添加(或删除)的项目,并仅创建或销毁更改的内容,这意味着您不会失去对输入字段的关注:)

链接中所示,您还可以修改数组以包含唯一的对象,例如使用[(ngModel)] =“value.id”,但这可能不是您需要的.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐