【问题标题】:Is it possible to customize Angular 2's: NgModel data flow with 2 one way data bindings?是否可以使用 2 单向数据绑定自定义 Angular 2:NgModel 数据流?
【发布时间】:2016-08-29 18:29:03
【问题描述】:

在 Angular 2 中,是否可以将 ngModel 用作某种:“2 个单向数据绑定”?

我正在尝试从用户 LinkedIn 导入建议,然后将其与表单一起发布到另一个模型。

angular docs 中声明:

在 [(ngModel)] 内部,我们可以通过单独绑定到输入元素的 value 属性和输入事件来获得相同的结果。

<!--From angular.io-->
<input [value]="currentHero.firstName"
       (input)="currentHero.firstName=$event.target.value" >

我想也许有一种方法可以将 ngModel 与 [value] 和 (input) 一起用作两个单独的数据流,这意味着导入是从 user 模型和然后发布到公司模型。

以下是我的代码中的一个 sn-p:

<div class="form-group">
    <label for="industry">Industry</label>
    <input type="text" class="form-control" 
        [value]="user.linkedIn.positions.values[0].company.industry" 
        (input)="company.industries=$event.target.value" 
        name="industry" required>
</div>

例如,我之前的表单代码如下所示: (没有任何导入或任何东西。我的基本后请求工作正常,新公司已提交到我的数据库。)

<input type="text" 
    class="form-control" 
    [(ngModel)]="company.industries" 
    name="industry" required #name="ngModel">

一些打字稿代码:

getCurrentUser() {
this.userService
  .getCurrentUser()
  .then(user => this.user = user)
  .catch(error => this.error = error);
}

submitted = false;
  onSubmit() { 
    this.submitted = true;
    this.companyService
      .save(this.company)
      .then(company => {
        this.company = company;
        this.goBack(company);
      })
      .catch(error => this.error = error);
  }

当发出实际的 http 请求时,服务器上的我的节点应用程序崩溃了,当然,这可能根本不可能使用 ngModel 来实现,但我不知道,所以我开始了这里。换句话说...... ngModel 必须仅绑定到角度 2 中的一个模型,还是我可以根据需要对其进行自定义以导入数据并将此数据发送到另一个模型?我希望这是有道理的。

所以基本上我的问题是:使用 ngModel 进行这种数据绑定是一种平滑的方式,还是我可以这样做?

另外:从 LinkedIn 导入时,我能够从我的 "users" 模型中获取正确的数据。

【问题讨论】:

    标签: angular angular2-ngmodel


    【解决方案1】:

    我不太明白你的问题。也许你正在寻找

    [ngModel]="company?.industries" (ngModelChange)="company.industries = $event" 
    

    【讨论】:

    • 我只是想从表单输入中获取值,然后使用 ngModel 与我的表单一起提交。当更改 ngModel 的 [value] 以从另一个地方(如linkedIn)导入值时,它会使应用程序在服务器上崩溃。 (与仅将 ngModel 绑定到 company.industries 并忽略整个linkedIn 部分相反)我会研究 ngModelChange 看看它是否可以为我指明正确的方向,谢谢!
    猜你喜欢
    • 2016-10-12
    • 2017-07-22
    • 1970-01-01
    • 2017-04-29
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 2016-12-18
    相关资源
    最近更新 更多