【问题标题】:Another Angular2 Two-Way DataBinding (with Meteor)另一个 Angular2 双向数据绑定(使用 Meteor)
【发布时间】:2017-05-10 03:37:37
【问题描述】:

我已经浏览了关于 Angular2 上的数据绑定的一些问题,但我无法得到我期望的结果。我也是 Angular 和 Meteor 的新手。

这是我的 app.component.html 中的内容

<form [formGroup]="getNameForm" (ngSubmit)="getName()">
  <label>ID: </label><br>
  <input type="text" formControlName="userID"><br>
  <button type="submit">Get</button>
</form>

<div (ngModel)="basicUser">
 <label name="basicUserName">{{basicUser.userName}}</label><br>
</div>

app.component.ts 中有什么

...
export class AppComponent implements OnInit {
basicUser: BasicUser = { ... }
...

getName(): void {
...
  Meteor.call('api.getName',{
    userId: this.getNameForm.value.userID
  }, (err, res) => {
    if (err) {
      console.log(err);
      alert(err);
    } else {
      console.log(res);
      this.basicUser = res;
  });
...
}

所以我期望发生的是,当我单击 getNameForm 的提交按钮时,标签 basicUserName 将使用来自 basic.userName 的值进行更新。相反,屏幕上的数据没有刷新。

但是,如果我单击输入文本框,然后单击页面上的其他位置,标签的值会正确刷新。我希望在单击表单提交时发生这种情况,因为标签中使用的变量在执行按钮方法时被修改。

在这里查找一些看似相关问题的答案,我尝试将this.ref.detectChanges() 包含在方法的最后一行中。这没有帮助。

这里的一些其他答案建议使用ngModel,这是我现在使用代码的地方,但这也不是诀窍。我觉得我错过了一些明显的东西。

【问题讨论】:

    标签: angular meteor typescript data-binding 2-way-object-databinding


    【解决方案1】:

    实际上这里的主要问题是我们同时使用 angular 2 和流星,两者都在不同的区域。所以角度不会检测到超出其区域的变化。您可以使用此方法解决此问题。

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

    在你的构造函数类型中使用这个

    constructor(private ngZone: NgZone) {}
    

    并像这样使用 ngZone 你想通过角度检测哪些值

      generate_head_list_data(){
            var self = this;
             Meteor.call('refresh_graph_list', self.all_csvdata, self.newGraphdata, (error, response) => {
                    if (error) {
                        console.log(error.reason);
                        self.ngZone.run(() => { <-- put you code inside ngZone in which you are getting issue in rendering
                            self.processingStart = false;
                        });
                    } else {
                        self.ngZone.run(() => {
                            self.processingStart = false;
                        });
                        console.log(response);
                    }
                });
        }
    

    这会解决你的问题:)

    【讨论】:

    • 效果很好,谢谢!标记回答。 NgZone 是要走的路。
    猜你喜欢
    • 2015-08-08
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2017-06-19
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多