Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Change detection not showing unless clicked

I have an component in which you can enter some search terms and it will filter the content using a *ngFor loop. The trouble is when I enter a search term I need to click the screen for the update to take effect visually.

Here is the part of the html code in which the loop occurs:

    <li *ngFor="let item of posts | reverse; let i = index; ">
        <div class="media" *ngIf="item.doesContainTags(searchTags)">

The code that executes on the input field where you enter the tags to search for is:

 updateSearchTags() {
    event.stopPropagation();
    // sorter is what is types into the search by tag input field
    this.searchTags = this.sorter.split(',');
 }

Here is the static function on the post object:

  doesContainTags(searchTags: string[]): boolean {

    let array = this.tags.split(',');
    if(!array || array.length === 0) {return false;}
    if(!searchTags || searchTags.length === 0) {return false;}

    for(let searchTag of searchTags){
         if(array.indexOf(searchTag) === -1) {

        } else {
        return true;
        }
    }
    return false;
 }

Here is the code which gets the posts that are looped over:

            this.postsService.subscribeAllPosts()
            .do(console.log)
            .subscribe( posts => this.posts = posts);

Here is the code in the postsService which gets the observable:

 subscribeAllPosts(): Observable<Post[]> {
    return this.af.database.list('posts')
    .map(Post.fromJsonList);
 }

So all this works but the change is not showing unless I click the screen. Is there a way to manually call it to update. I was thinking I could call this manually within the updateSearchTags function which is updated after typing in the search by tags input but I am unsure of what code would do this.

  • Update, I have changed the event to a keypress event. Now however I am trying to get this event to happen after the two way binding happens as it is now just doing it before the binding occurs. It just shows each char after you click the next one.

Update 2 - Found the keyup event. Issued sorted.

like image 985
Pete Avatar asked Oct 28 '16 17:10

Pete


1 Answers

Try to use ChangeDetectorRef as shown below to update data. Possible reason could be that you're service code is running out of Angular framework.

import { Component, ChangeDetectorRef } from 'angular2/core';

@Component({
  (...)
})
export class MyComponent {
  constructor(private cdr:ChangeDetectorRef) {}   //<<###################### here

  this.postsService.subscribeAllPosts()
                   .do(console.log)
                   .subscribe( posts => {

                        this.posts = posts; 
   
                        this.cdr.detectChanges();  //<<<#################### here
                });
}
like image 137
Nikhil Shah Avatar answered Oct 24 '22 11:10

Nikhil Shah