3

The array that is used in the ngfor loop, when it is updated how do you get Angular2 to re-run that expression? Currently it wont output anything due it running at the beginnin with an empty array - once updated (the array has been changed) the ngfor expression is not re-run - which is the desired functionality. How is this done?

For example in the component HTML;

<option *ngFor="let user of users" [value]="user.id">{{user.name}}</option>

In the component TS we have declared a property;

users: IUser[] = [];

In ngOnInit we have a call to a TS service that returns us the user data;

this.userDataService.getUsers().subscribe(data => {
    this.users = data;
});

Updated code example;

@Component({
  selector: 'app-manage-user',
  templateUrl: './user-form.component.html',
  providers: [UsersDataService]
})
export class UserFormComponent implements OnInit {

  constructor(private userDataService: UsersDataService) {

  }

  users: IUser[] = []; 

  ngOnInit() {
    this.userDataService.getUsers().subscribe(user => {
      this.users = user;
    });
  }
}
3
  • what do you mean with "updated"? When you "update" your array, why not call this.userDataService.getUsers.... method? Commented Dec 23, 2016 at 8:32
  • We can't call getUsers function and assign to the user property directly, because getUsers returns an observable. Commented Dec 23, 2016 at 8:54
  • 2
    *ngFor checks the array for changes every time change detection is run and updates the DOM accordingly. Are you using exactly the ngOnInit code above or is it more complex in your real code? Commented Dec 23, 2016 at 9:00

3 Answers 3

4

You can use ChangeDetectorRef to detect changes.

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

Inject it in your constructor and call detectChanges() method when the array's value is changed:

  constructor(private userDataService: UsersDataService, private changeDetector: ChangeDetectorRef) {

  }

  users: IUser[] = []; 

  ngOnInit() {
    this.userDataService.getUsers().subscribe(user => {
      this.users = user;
      this.changeDetector.detectChanges();
    });
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Ah yes I forgot about the change detector! Thank you very much indeed.
0

I would suggest to use it like :

<select *ngIf="users.length >0">
<option *ngFor="let user of users" [value]="user.id">{{user.name}}</option>
</select

Comments

0

You can check because request fast array not update:

ngOnInit() {
    this.userDataService.getUsers().subscribe(user => {
      if(user){
        this.users = user;
      }
    });
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.