Search code examples
htmlangulardata-bindinginnerhtml

Angular 5 - Bind a component selector with InnerHtml


I have a component1 selector that I called "app-component1".

@Component({
   selector: 'app-component1',
   templateUrl: './test-widget.component.html',
   styleUrls: ['./test-widget.component.scss'] })

So to call the html of this component I usually use:

<app-component1></app-component1>

and it works perfectly fine.

Now from another component2 I have the following variable:

variableToBind = "<app-component1></app-component1>";

And In the html of component 2 I used the following:

<div [innerHtml]="varibableToBind"></div>

The html code binding isn't working. Is is possible to help me understand why and maybe help me find another alternative?


Solution

  • Thanks Everyone for the suggestions, I actually just find the answer to this:

    This can't work because innerHtml is rendered AFTER Angular's compiled the templates. That means that it doesn't understand your selectors at this point of time.

    If you guys want to load a component (or any content) dynamically, you should use *ngIf. It worked perfectly fine for me.