【问题标题】:Angular lost the most important thing, the binding?Angular 失去了最重要的东西,绑定?
【发布时间】:2020-04-21 12:50:17
【问题描述】:

我想知道我认为最重要的 Angular 绑定发生了什么,在下面的代码中,如果我修改数组项,则没有更多绑定,如果我输入 emails[i] 我已经想想有点难看,每个数字的输入都会失去焦点。谢谢!

app.component.html

<div>
  <ul>
    <li *ngFor="let email of emails; let i = index; trackBy:trackByfn">
      <input [(ngModel)]="email">
    </li>
  </ul>
  <span>{{ emails | json }}</span>
</div>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  emails: string[] = ['test@mail.com'];

}

【问题讨论】:

    标签: angular binding


    【解决方案1】:

    您可以将其转换为使用 ReactiveForms。

    模板

    <form [formGroup]="form" novalidate>
      <div>
        <ul>
          <li formArrayName="emails" *ngFor="let email of form.get('emails').controls; let i = index; trackBy:trackByfn">
            <input [formControl]="email">
          </li>
        </ul>
        <span>{{ form.value | json }}</span>
      </div>
    </form>
    

    组件

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      form:FormGroup = this.fb.group({
        emails: this.fb.array(['test@mail.com'])
      });
    
      constructor(
        private fb:FormBuilder
      ) {
    
      }
    
      trackByFn(index, item) {
        return index;
      }
    }
    

    Working Stackblitz.

    【讨论】:

    • 感谢您的提示,它成功了。但我只是认为它为以前如此简单的东西写了很多东西。更不用说我的代码实际上并不像我发布的那样简单以方便答案。在我的代码中,Emails 只是一个已经在 FormGroup 中的类的属性。
    • 你说得对。有点不幸的是,数组并不真正适用于模板驱动的表单(这是 ngModel 的一部分)。但是考虑到将模型与模板分开通常是一种很好的做法,并且样板文件并不多,因此反应式表单是一个不错的选择。特别是当验证发挥作用时。对于根本不需要验证的表单,这有点开销。
    【解决方案2】:
    trackByFn(index, item) {
      return index;
    }
    

    现在,当您更改集合时,Angular 可以根据唯一标识符跟踪已添加或删除的项目,并仅创建或销毁已更改的项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-01
      • 2021-08-02
      • 2021-04-25
      • 1970-01-01
      • 2018-08-25
      • 2017-02-26
      • 2019-02-17
      • 2017-03-28
      相关资源
      最近更新 更多