Invoke a method in Angular2 using On load on div element and pass data from html as a parameter

I have a bunch of div elements whose background color has to be set according to data from the angular component.For example, if the data is 0.5 and below, it should be green and so on.For that, the data(s.score) is available in the HTML template.But I need a way to pass this data as a parameter to a function which should be invoked on a load of this div.The class name of div elements is "card" Here is my div structure:

<div *ngFor="let s of res1  let i=index" style="display:inline-block;padding:10px;" [dragula]='"bag-task1"'>
         <div class="container">
             <div  class="card" id="{{'card_'+i}}" #cardDiv (click)="flip(cardDiv.id,$event)" >
                 <div class="front">
       <div style="border:1px solid white;text:white">
         <h3>{{s.Unit}}</h3>
       </div>

           <div style="display:inline-block">
          <div style="display:inline-block"> <img src="./assets/O2.png" style="width:40px;height:40px;float:left;border:0px"/>
            <h3 style="margin-left:40px;width:30px">{{s.sao2}}</h3></div>
              <div style="display:inline-block">
                <img src="./assets/bp_icon.png" style="width:40px;height:40px;float:left;border:0px"/>
                <h3 style="float:right;margin-left:20px;width:30px">{{s.systemicmean}}</h3></div>
          </div>

       </div>
    </div>

Any help is much appreciated. Thanks in Advance. Supraja

1 answer

  • answered 2018-01-11 21:05 masterfloda

    Why don't you just create a public function in your component, that returns a string class name (or if you want to do it dirty, a hex color code that you could use in a background-color style attribute?

    https://stackblitz.com/edit/angular-qflqpp?file=app%2Fapp.component.ts

    getBackgroundClass(s: Element): string {
      if (s.score < 0.5) {
        return 'green';
      }
      return 'red';
    }