【问题标题】:Bind one data field to another in Angular?在Angular中将一个数据字段绑定到另一个?
【发布时间】:2020-11-25 09:31:58
【问题描述】:

Angular 有一种非常好用且易于使用的方式将 HTML 元素的值绑定到数据字段,例如:

<input name="firstName" [(ngModel)]="firstName"/>

所以我在文本字段中输入的任何内容都会设置为我的 Angular 组件中的字段 firstName,并且无论组件将其设置为自动显示在页面上的输入字段中。

但是如果我需要将数据字段绑定到另一个字段怎么办?在这种特殊情况下,有一个作为字符串列表的支持数据字段,将值的每个字母(在本例中为“firstName”)作为其自己的字符串。如果这是 C#,我只需执行以下操作:

private List<string> firstNameLetters { get; set; }
public string firstName
{
  get { return string.Join("", firstNameLetters); }
  set { firstnameLetters = value.Select(c => c.ToString()).ToList(); }
}

但是我如何在 Angular 中做到这一点?我发现了这个问题:How do I bind the data in an input field to another input field on Angular?

但这对我来说似乎是阴险的 JavaScript 诡计。有没有更 Angulary 的方式来做到这一点?

【问题讨论】:

  • firstNameLetters 会被绑定到另一个文本类型的input 上吗?就像你有另一个输入 [(ngModel)]="firstNameLetters"?
  • 没有。它只会绑定到 Angular 组件本身的不同字段。然后,Angular 组件使用它来将数据作为 JSON 对象发送到 ASP.NET 控制器。
  • 是的,这看起来更 Angulary,谢谢。我必须使该解决方案适应我的 Angular 代码。
  • 要获得更多角度,您应该真正考虑反应形式。然后,您可以使用 RxJS 根据更改响应式更新值。

标签: angular properties


【解决方案1】:

您可以尝试使用input 事件来更新变量:

  firstNameLetters: string[] = [];

  // ...

  handleInput($event) {
    this.firstNameLetters = this.firstName.split('');
  }
  <input name="firstName" [(ngModel)]="firstName" (input)="handleInput($event)" />

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多