Angular 4 | How to dynamically inject a directive when click?

Viewed 4525

Good day, how can achieve to inject a custom directive when the button is being click?

See my code below..

<ng-container *ngFor="let apidata of zoneOne; let i = index">
  <div class="box" *ngIf="(i < 5)" **insert directives here**>
    <div class="box-holder">
      <span id="AssignmentNumber">{{apidata.Assignment}}</span>
    </div>
  </div>
</ng-container>  
<button class="viewMore" (click)="viewMoreClick()">View more..</button>

this is just a simple toggle event. i just having trouble figuring out how to do this because it all toggle the element when i put my function on each div. i just want to show the div when the specific div is being click..

1 Answers

What you can do is :

<p [appHighlight]="toggleDirective">
  Start editing to see some magic happen :)
</p>

<button (click)='toggleDirective=!toggleDirective'>Toggle</button>

Based upon true and false you can also change the behavior of the directives.

export class HighlightDirective implements OnChanges {
    @Input('appHighlight') highlightColor: boolean;

    constructor(private el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }

    ngOnChanges(){
      this.el.nativeElement.style.backgroundColor = this.highlightColor ? 'yellow' : '';
    }
}

WORKING DEMO

Related