Mohammad Dayyan
Mohammad Dayyan

Reputation: 22408

Inner HTML of ng-container, Angular 4?

I want to dynamically place an html code in my html code, So I write the following code:

<ng-container [innerHTML]="buttonIcon"></ng-container>

Angular says innerHTML is not valid attribute for ng-container
I don't want to use third html tag like follows:

<div [innerHTML]="buttonIcon"></div>

So how can I insert html codes without any tag inner html binding?

Upvotes: 23

Views: 22087

Answers (4)

Pierre Chavaroche
Pierre Chavaroche

Reputation: 1293

[outerHTML]

will do the trick to replace the outer element.

In your case

<div [outerHTML]="buttonIcon"></div>

It's true, that it's important to have a clean HTML structure for e.g. keeping CSS rules as simple as possible.

Upvotes: 34

Javier Rojano
Javier Rojano

Reputation: 982

If for any reason you need to replace the DOM element you can use a div with an id and then use the @ViewChild decorator and ElementRef to get access to the nativeElement from the controller and set the outerHtml property.

app.component.tml

<div #iconButton></div>

app.component.ts

import { Component, ViewChild, ElementRef, ViewEncapsulation, AfterViewInit }from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent  implements AfterViewInit{
   @ViewChild('iconButton')
    iconButton: ElementRef;

    ngAfterViewInit(){
      this.iconButton.nativeElement.outerHTML = '<button>My button</button>'
    }
}

We need to use none as encapsulation policy because our template only includes the div to be replaced.

Stackblitz example: https://stackblitz.com/edit/angular-fa1zwp

Upvotes: 2

phil294
phil294

Reputation: 10852

** Please read the comments. This answer might be wrong. I dont know, have not looked into it again **

ng-container does not get rendered to html, it is a mere structural directive.

The Angular is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

So there is no element to put html into. You need to work with a sub-div. If there is no need for a sub-div in your opinion, then you could most probably also just replace ng-container with div itself and not use the container at all.

Upvotes: 4

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can use ngTemplate:

<ng-template #buttonIcon>
    <div> Your html</div>
</ng-template>
<ng-container 
   *ngTemplateOutlet="buttonIcon">
</ng-container>

Upvotes: 18

Related Questions