Search code examples
angularsvgrect

Angular4 svg rect pass value dynamically


I am building a "BarsChartComponent" and I am using svg rect to display bars. What I am trying to do is to pass width value dynamically.. Code bellow does not display any result:

Component object to display:

items:any=[{Country:"Canada", Value:"1000"}, 
               {Country:"USA", Value:"800"},
               {Country:"Costa Rica", Value:"400"},
               {Country:"Brazil", Value:"500"}];

Component template:

  <svg class="chart" width="420" height="150" aria-labelledby="title" role="img">
    <ng-template *ngFor="let item of items">
        <rect [attr.width]="item.Value" height="19" y="20"></rect>
    </ng-template>
    </svg> 

I guess it is a syntax error.. Any help is welcome!


Solution

  • Use ng-container instead of the ng-template

    <svg class="chart" width="420" height="150" aria-labelledby="title" role="img"> 
      <ng-container *ngFor="let item of items">
        <rect [attr.width]="item.Value" height="19" y="20"></rect> 
      </ng-container>
    </svg>  
    

    Demo