2

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..

Jydon Mah
  • 383
  • 1
  • 9
  • 29
  • 4
    Possible duplicate of [How to dynamically add a directive?](https://stackoverflow.com/questions/41298168/how-to-dynamically-add-a-directive) – Daniel Nov 23 '17 at 03:37

1 Answers1

1

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

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • this works fine but what if i add another `

    Start editing to see some magic happen :)

    ` i want only single of them will be highlights when it is being clicked. lets say i have another button specific for each

    element

    – Jydon Mah Nov 23 '17 at 05:16
  • @JydonMah, directive will work differently for all the elements, and there will be always some conditions based upon you will add or remove directive,right , then just paste the condition. please check updated demo – Vivek Doshi Nov 23 '17 at 05:21
  • ahh i understand now. thanks for this man but i want to achieve is like attached and detached a directive when the button is being click. but i dont think it will be a good practice creating multiple directive to target specific element just to show and hide an element. just like show1=false, show2=false, then – Jydon Mah Nov 23 '17 at 05:45
  • this is the same thing, all you need is adapt the way, :) – Vivek Doshi Nov 23 '17 at 05:46
  • @JydonMah, will you please upvote the answer and also accpet if it gives answer to your question ? – Vivek Doshi Nov 23 '17 at 06:19