【问题标题】:Dynamic input text (ngModel) and variables for Angular. Lagging input?Angular 的动态输入文本 (ngModel) 和变量。输入滞后?
【发布时间】:2021-11-30 21:53:40
【问题描述】:

我正在尝试为分配给数组的描述添加多个输入文本字段,但在此处使用 ngModel 时遇到问题。在下面的代码中,当输入文本框时,它会失去焦点,我一次只能输入一个字符——几乎就像它的滞后一样。将数组输出到控制台时似乎可以工作,但是,当我添加另一个文本字段元素而不是第三个元素为空白时,它将返回前一个值。

component.html

<div class="input-group mb-3" *ngFor="let descriptions of descriptionPool;let i = index">
          <span class="input-group-text" id="inputGroup-sizing-lg">Description #{{ i + 1 }}</span>
          <textarea class="form-control text-wrap" placeholder="Posts will use this description." [(ngModel)]="descriptionPool[i]" name="somename"></textarea>
          <button class="btn btn-primary text-light" (click)="addDescriptionField(descriptionPool[i])"> + </button>
          <button class="btn btn-primary text-light" (click)="delDescriptionField(i)"><i class="fas fa-trash-alt"></i></button>
</div>

component.ts

descriptionPool: Array<string> = [];

ngOnInit(): void {
     
      this.descriptionPool.push('');
      
  }

addDescriptionField(description: string) {
    console.log('descriptions? ' + JSON.stringify(this.descriptionPool));
    this.descriptionPool.push(description);
  }

  delDescriptionField(index: any) {
    this.descriptionPool.splice(index, 1);
    console.log('after deleting: ' + JSON.stringify(this.descriptionPool));
  }

删除功能按预期工作。 :)

【问题讨论】:

  • 问题似乎出在 ngmodel 中

标签: angular typescript ngmodel


【解决方案1】:

当您输入一些文本时,角度 ngOnChange 侦听器将运行,因此 ngFor 索引将重新呈现并且焦点将丢失。为了避免这个问题,可以将 trackFn 添加到 ngFor。有关该主题的更多详细信息,请参阅https://angular.io/api/core/TrackByFunction。在您的问题的代码解决方案下方:

在您的 html 代码中定义 ngFor 一个 trackFn 函数,该函数将对应于 .ts 文件中声明的 trackByFn 函数。

<div class="input-group mb-3" *ngFor="let descriptions of descriptionPool;let i = index; trackFn: trackByFn
">
      <span class="input-group-text" id="inputGroup-sizing-lg">Description #{{ i + 1 }}</span>
      <textarea class="form-control text-wrap" placeholder="Posts will use this description." [(ngModel)]="descriptionPool[i]" name="somename"></textarea>
      <button class="btn btn-primary text-light" (click)="addDescriptionField(descriptionPool[i])"> + </button>
      <button class="btn btn-primary text-light" (click)="delDescriptionField(i)"><i class="fas fa-trash-alt"></i></button>

并在ts文件中声明上面提到的trackByFn函数:

trackByFn(i: number, items: any) {
return i //returning the index itself for avoiding ngFor to change focus after ngModelChange
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-28
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多