** ngClass and ngStyle **
<div *ngIf="onlyOdd">
<ul class="list-group">
<li
class="list-group-item" *ngFor="let item of OddNumbers"
[ngClass]="{oddNumber: item % 2 !== 0}"> <!-- ngClass directivies oddNumber is css class-->
{{item}}
</li>
</ul>
</div>
<div *ngIf="!onlyOdd">
<ul class="list-group">
<li
class="list-group-item" *ngFor="let item of evenNumber"
[ngClass]="{oddNumber: item % 2 !== 0}"> <!-- ngClass directivies oddNumber is css class-->
{{item}}
</li>
</ul>
</div>
** Creating a Basic Own Attribute Directive **
import {Directive, ElementRef, OnInit} from "@angular/core";
@Directive({
selector:'[appBasicHighLight]' //this will now recognize as attributes directives
})
export class BasicHighLightDirective implements OnInit
{
constructor(private elementref:ElementRef){
}
ngOnInit(){
this.elementref.nativeElement.style.backgroundColor = 'green';
}
}
It is not best practices to directly access the element/DOM by injecting in constructor. Below is the another example injecting using Renderer. This is the better approch for access the DOM directly. Why it is better? let me explain, Angular not limited to browser worker but for example in service which is the environment where you will not get the access of the DOM. So it if you try to change the DOM As we did previous example you might get an error in some cases. Still it is best practices to access the DOM using Renderer2.
import {Directive, OnInit, Renderer2, ElementRef} from '@angular/core';
@Directive({
selector: '[appBetterHighlight]'
})
export class BetterHighlightDirective implements OnInit{
constructor(private elementRef:ElementRef,private renderer:Renderer2) {
}
ngOnInit(){
this.renderer.setStyle(this.elementRef.nativeElement,'background-color','blue');
}
}