Search code examples
angularasynchronouseventemitter

Update UI html from async list


I'm trying to understand what I made. I have a async list of items (different number each time). I'm trying to set each of them as different div using *ngFor

details.html

<div class="container row">
    <div id="letter">
        <div id="lines_container">
            <div *ngFor='let sentence of sentences' id="line_{{i}}" class="new-line glow">
                {{sentence.name}}
            </div>
        </div>
    </div>
</div>

DetailsComponent.ts

@Component({
    selector: 'app-details',
    templateUrl: 'details.html',
    styleUrls: ['details.scss']
})
export class DetailsComponent implements OnInit {
  sentences: string[];

  constructor(private data: DetailsService, private ravenDataService: RavenDataService) { }

  ngOnInit(): void {
    this.data.sentences.subscribe(sentences => {
      console.log(sentences);
      this.sentences = sentences;
    });
  }
}

I can see the log after few seconds that printed with my sentences but it's not update my HTML page. I also tried to use the async pipe with no success

<div *ngFor='let sentence of sentences | async' id="line_{{i}}" class="new-line glow">

Solution

  • I think it's just a typo, please try with async pipe and don't use subscribe.

    @Component({
        selector: 'app-details',
        templateUrl: 'details.html',
        styleUrls: ['details.scss']
    })
    export class DetailsComponent implements OnInit {
      sentences$;
    
      constructor(private data: DetailsService, private ravenDataService: RavenDataService) { }
    
      ngOnInit(): void {
        this.sentences$ = this.data.sentences
      }
    }
    

    and

    <div *ngFor='let sentence of sentences$ | async' id="line_{{i}}" class="new-line glow">
    

    Always mark your streams with $ sign at the end, it's a common convention