1

I am trying to add dropdown to a div. The html code (dropdown is an example) is dynamic code. Even though on clicking it shows the dropdown button but the dropdown isn't working. Following is my code from component file

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@ViewChild('showfilters') el:ElementRef;


this.el.nativeElement.innerHTML = this.el.nativeElement.innerHTML + `
<div class="dropdown " dropdown>
   <a class="dropdown-toggle  text-light" dropdownToggle> New Dropdown</a>
   <div class="dropdown-menu mt-2 mr-3" *dropdownMenu>
     <a class="dropdown-item"> Profile</a>
     <a class="dropdown-item" href="#">Another action</a>
     <div class="dropdown-divider"></div>
       <a class="dropdown-item"><i class="fa fa-sign-out"></i>New</a>
   </div>
</div>
`;

My html <div class="showfilters" #showfilters>

I have created an example on StackBlitz too.

Saad Bashir
  • 4,341
  • 8
  • 30
  • 60
  • your problem is add dynamic directive to div https://stackoverflow.com/questions/45084292/dynamically-mount-angular-2-directive – Hien Nguyen May 06 '20 at 08:57
  • So based on the answer in the link I cant add dropdown dynamically? – Saad Bashir May 06 '20 at 09:00
  • You can... it's just not as simple as appending HTML to the document (which is never a good idea in angular anyway). –  May 06 '20 at 12:48

1 Answers1

0

I strongly recommend not adding HTML to your component this way, instead you could just use *ngFor with a small hack.

Forked: https://stackblitz.com/edit/bootstrap-dropdown-angular-xcg7xf

The hack... *ngFor="let dummy of ' '.repeat(dropDownCount).split('')"

basically creates an array that has the exact length of your variable so that *ngFor can iterate through it.

If you insist on having to add HTML through your component, you may have to take a look at this: Equivalent of $compile in Angular 2