Using ngClass to color titles of newly added articles

This snippet shows how to use ngClass to set the style during a given condition

  •         
    import {Component} from '@angular/core';
    
    
    @Component({
      moduleId: module.id,
      selector: "gf-list",
      templateUrl: "list.html"
    })
    export class ListComponent implements OnInit {
      
      
      constructor() {}
    
    
    	isNewDate(publishDate){
        		const testedDate = new Date(publishDate);
        		const nowDate = new Date();
        		let timeDiff = Math.abs(nowDate.getTime() - testedDate.getTime());
        		let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
      		return (diffDays < 14)
    	}
    
      
    }
            
        

  •         
    <StackLayout>
           <ListView [items]="articles$ | async">
                <template let-item="item">                  
                    <GridLayout  columns="*">
    
                        <GridLayout columns="auto,*,auto" rows="*,*" col="0" class="card">
                            <Image class="m-5"     
                                   horizontalAlignment="left" 
                                   rowSpan="2" 
                                   row="0" 
                                   col="0" 
                                   width="100" height="100"  
                                  [src]="item.imagepath.length>0 ? item.imagepath : '~/assets/default.png'">
                            </Image>
                            <Label class="m-5 h3"  
                                   [ngClass]="{newDate : isNewDate(item.date)}"  
                                   class="oldDate" 
                                   col="1" row="0" 
                                   [text]='item.title'>
                          </Label>
                            <Label class="m-10 font-awesome"   style="color:black;" col="2"  row="0" text='&#xf15c;'></Label>
                            <Label class="m-10 font-awesome h5" col="1"  horizontalAlignment="right" colSpan="2" row="1" [text]='(item.date*-1) | date:"longDate"'></Label>
                        </GridLayout>                 
                    </GridLayout>
                </template>
        </ListView>
            
        

  •         
    .oldDate {
        color:black
    }
    .newDate {
        color:red
    }
            
        

  • In this snippet, I want to show how to use ngClass in Angular to set a style according to a certain condition. In this example, we have a list of articles, and if an article is published less than two weeks prior, their titles will appear in red.