Another Angular2 Two-Way DataBinding (with Meteor)

72 views Asked by At

I've browsed through some of the question here on Data Binding on Angular2, but I'm not able to get the result I was expecting. I'm also new to both Angular & Meteor.

Here's what I have in my 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>

And what's in 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;
  });
...
}

So what I expect to happen is when I click the submit button for the getNameForm is for the label basicUserName to be updated with the value from basic.userName. Instead, there is no refresh of the data on the screen.

However, if I click on the input text box & then click somewhere else on the page, the value of the label refreshes correctly. I would want this to happen on click of the form submit since the variable that is used in the label is modified on execution of the button's method.

Looking up some answers to seemingly related questions here, I gave this.ref.detectChanges() a try by including it as the last line on the method. That didn't help.

Some other answers here suggested using ngModel, which is where I'm at right now with the code, but that's not doing the trick either. I feel like I'm missing something obvious.

1

There are 1 answers

1
Amit kumar On BEST ANSWER

Actually here main problem is we are using angular 2 and meteor together and both are in different zones. so angular don't detect change which are outside of its zone.you can solve this problem using this method.

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

in you constructor type use this

constructor(private ngZone: NgZone) {}

and use ngZone like this which values you want to detect by angular

  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);
                }
            });
    }

this will solve your problem :)