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?
You can use ngTemplate:
<ng-template #buttonIcon>
<div> Your html</div>
</ng-template>
<ng-container
*ngTemplateOutlet="buttonIcon">
</ng-container>
** 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.
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
[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 eg keeping CSS rules as simple as possible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.