Alexandr Belov Alexandr Belov - 4 years ago 128
TypeScript Question

Render dynamic array in the view Angular2

I've got a dynamic array which I want to render in the view of a component when some items added / removed inside.

The array is rendered by

method in my App Component (ts):

import { Component, OnInit } from '@angular/core';
import { CartService } from './cart/cart.service';

import '../style/app.scss';

selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
export class AppComponent {
cartItems: any;
image: any;
item: any;

constructor(public cartService: CartService) { }

this.cartService.cart$.subscribe((val) => {
console.log(this.cartService.cartArr)//console shows the array properly, but nothing is shown in the view if I remove "console.log"



"The view" for the array inside my App Component (html):

<ul class="cart">
<li class="cart__item" *ngFor="let item of cartArr">

My CartService:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export class CartService {
public cart$ = new BehaviorSubject(null);
public cartArr = [];

constructor(){ }

public addToCart(prod) {

So I wonder how to render the array in the Component html and why my code isn't working outside the console?

Answer Source


As said @TuongLe in comment if you manually subscribe to your observable then you should to call unsubscribe in ngOnDestroy to prevent memory leak.

You can either

1) set array value:

cartItems: any[];

cartSubscription: Subscription;

ngOnInit() {
  this.cartSubscription = this.cartService.cart$.subscribe((val) => {
    this.cartItems = val;

ngOnDestroy() {


*ngFor="let item of cartItems"


2) use async pipe like:

*ngFor="let item of cartService.cart$ | async"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download