编程语言
首页 > 编程语言> > javascript – Angular2动态输入字段在输入更改时失去焦点

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”,但这可能不是您需要的.

标签:html,javascript,jquery,angular,angular2-forms
来源: https://codeday.me/bug/20190918/1810843.html