Angular 可编辑字符串列表
我需要字符串的可编辑数组:用户必须能够添加/删除/编辑任意数量的字符串 我的解决方案适用于对象数组,但不适用于字符串数组 请给我解释一下-为什么输入会失去对每个字符的关注Angular 可编辑字符串列表,angular,input,angular8,angular-ngmodel,Angular,Input,Angular8,Angular Ngmodel,我需要字符串的可编辑数组:用户必须能够添加/删除/编辑任意数量的字符串 我的解决方案适用于对象数组,但不适用于字符串数组 请给我解释一下-为什么输入会失去对每个字符的关注 import { Component } from '@angular/core'; interface Foo { str: string; } ; @Component({ selector: 'my-app', template: ` <p> Notes:{{notes | json}} <
import { Component } from '@angular/core';
interface Foo { str: string; } ;
@Component({
selector: 'my-app',
template: `
<p> Notes:{{notes | json}} </p>
<p> Objects:{{objects | json}} </p>
<button (click)="addItem()" >Add new</button>
input loses
<p>Objects:</p>
<div *ngFor="let obj of this.objects; let i = index;" >
Works :<input [(ngModel)]="objects[i].str" [ngModelOptions]="{standalone: true}" >
</div>
<p>Notes:</p>
<div *ngFor="let str of this.notes; let i = index;" >
It does not work because it loses focus:<input [(ngModel)]="notes[i]" [ngModelOptions]="{standalone: true}" >
</div>
`
})
export class AppComponent {
private notes: string[]=[];
private objects: Foo[]=[];
addItem() {
this.notes.push('');
this.objects.push({str: ''});
}
}
从'@angular/core'导入{Component};
接口Foo{str:string;};
@组成部分({
选择器:“我的应用程序”,
模板:`
注:{Notes | json}
对象:{{Objects}json}
新增
输入丢失
对象:
作品:
注:
它无法工作,因为它失去了焦点:
`
})
导出类AppComponent{
私人票据:字符串[]=[];
私有对象:Foo[]=[];
附加项(){
这个。notes。push(“”);
this.objects.push({str:'});
}
}
Stackblitz链接:
为了让它按预期工作,需要解决什么问题?谢谢,因为每次插入字符时,数组中的字符串都会被新字符串替换,因此Angular会删除与该元素(在thr ngFor循环中)对应的DOM元素,并将其替换为新元素。你需要使用trackBy。或者,正如您在第一个示例中所做的,使用可变对象。谢谢@JBNizet,添加“trackBy”解决了这个问题。