Angular2 - change detection is not displayed unless clicked

I have a component where you can enter some search terms and it will filter the content using the * ngFor loop. The problem is that when I enter the search query, I need to click on the screen for the update to work visually.

Here is the part of the html code where the loop takes place:

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

The code that runs in the input field where you enter 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 for 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 that receives messages that loop:

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

Here is the code in postsService that gets observable:

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

So this all works, but the change does not appear unless I press the screen. Is there a way to manually call it for an update. I thought I could call it manually in the updateSearchTags function, which is updated after entering the input in the input tag, but I'm not sure which code will do this.

  • Update, I changed the event to a keypress event. Now, however, I am trying to get this event to happen after the two-way binding has occurred, as it now just does it before the binding occurs. It just shows each char after you hit the next one.

Update 2 - a keyup event was detected. Released sorted.

+6
source share
2 answers

Try using ChangeDetectorRef , as shown below, to update the data. A possible reason may be that your utility code ends with Angular.

 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 }); } 
+10
source

I used the event (keyup) instead of the change / blur / keypress event.

0
source

Source: https://habr.com/ru/post/1011824/


All Articles