Angular 5 adding html content dynamically
The ComponentFactoryResolver
's resolveComponentFactory
method accepts an Angular Component.
In your case, you are injecting HTML into your template, not a component. To inject HTML, save it in a variable and use the DomSanitizer
to either sanitize it or bypass the security check:
export class main_page {
data: SafeHtml;
constructor(private sanitizer: DomSanitizer) {}
ngOnInit(){
this.getDynamicREST().then((res)=> {
this.data = this.sanitizer.sanitize(res);
/* OR */
this.data = this.sanitizer.bypassSecurityTrustHtml(res);
})
};
}
Then, in your template:
<div class="top">
<div [innerHtml]="data"></div>
</div>
How to create and add html elements dynamically with angular
I'd suggest looking at the Tour of Heroes tutorial on the Angular web site to learn more.
You can create a list in your component, call it categories
, then add more categories when you click the addCategory
button. In your html template, you can loop through the categories and create an element for each of them.
I created a minimal example in a Stackblitz. Below is a rough example of how it can be done
Angular component
categories: string[] = [];
addCategory() {
this.categories.push('category');
}
HTML template
<div *ngFor="let category of categories">
{{category}}
</div>
How to dynamically add HTML element/content - Angular
I think in Angular, you define table based on your data. for example, you have fields array defining columns, and data array defines the what's actually in the table.
<table >
<thead>
<tr>
<th *ngFor='let key of this.fields'>{{key}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let row of this.data ' >
<td scope="row" *ngFor='let key of this.fields'> {{row[key]}} </td>
</tr>
</tbody>
</table>
when you need a new column, just push a new field into fields. like
fields.push('newcolumn');
when you need a new row, just do:
data.push({col1: '', col2:'', newcolumn: ''});
Dynamically add a div to elements with the same class using Angular
You're creating one element ( const child = document.createElement("div")
) then passing the same reference to all of your container elements ( .cart-list-item
).
So, it first move into the first element, then as the loop goes you take the same element ( const child...
) and move it to the next container.
So, just create that child element inside the loop, so you'll be create one new element for each container. Like this:
ngAfterViewInit() {
const elements = this.elem.nativeElement.querySelectorAll('.cart-list-item');
elements.forEach(element => {
let child = document.createElement("div");
child.addEventListener('click', this.onClick.bind(this));
child.classList.add('cart-list-value', 'delete-product');
this.renderer.insertBefore(element, child, element.childNodes[0]);
});
console.log(elements);
}
Dynamic HTML In Angular
You can use ViewChild
to add dynamic content in this case,
@ViewChild('myDiv', {static: false}) myDiv :ElementRef;
this.myDiv.nativeElement.insertAdjacentHTML('beforeend', '<button (click)="somefunction()" >Dyanamic Button</button>');
Check this stackblitz for more.
Using DOM Sanitizer:
<h4>Dynamic</h4><br>
<div contenteditable="true" [innerHTML]="dyanmicHtmlString"></div><br>
import { DomSanitizer } from '@angular/platform-browser';
constructor(private sanitized: DomSanitizer) {}
ngOnInit() {
this.dyanmicHtmlString = this.sanitized.bypassSecurityTrustHtml('<button (click)="somefunction()" >Dyanamic Button</button>');
}
Angular 5 add dynamic html file into DIV
We need to use the safehtml
for displaying the html.
- We need to create the Pipe for this.
safe-html-pipe.ts
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'safehtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {
}
transform(value): SafeHtml {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
component.ts
We need to import the pipe
import {Component, NgModule, Pipe, PipeTransform} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser'
import { SafeHtmlPipe } from './safe-html-pipe';
@Component({
selector: 'app-root',
template:
`<div [innerHtml]="safeHtmlContent | safehtml">
</div>"})`
export class AppComponent {
name:string;
safeHtmlContent : string;
constructor() {
this.name = 'Angular2'
this.safeHtmlContent = '<html><head><title>Hello safe</title></head><body><h1>hello world Hello Umesh</h1></body></html>';
}
}
Hope this helps :).
how to insert html with angular bindings dynamically
you can use another approch (something like this):
<button (click)="showHtml()">Insert</button>
<ng-container *ngIf="clicked">
<div id="text"><span (click)="......" [hidden]="' + ...... + '">'</div>
</ng-container>
and in you .ts you do:
@Input()
clicked:boolean =false;
showHtml(){
this.clicked=true;
}
it must work.
Angular2 add HTML to dynamic elements
What's the problem with this approach?
export class AppComponent{
@ViewChild('d1') d1:ElementRef;
@ViewChild('d2') d2:ElementRef;
@ViewChild('d3') d3:ElementRef;
constructor(private renderer:Renderer2) { }
runR(){
let change_this;
change_this= this.renderer.createElement('span');
this.renderer.addClass(change_this, 'change_this');
this.renderer.appendChild(this.d1, change_this);
}
}
Template:
<div class="dynamically_created_div unique_identifier" #d1></div>
<div class="dynamically_created_div unique_identifier" #d2></div>
<div class="dynamically_created_div unique_identifier" #d3></div>
Related Topics
Using HTML Anchor Link #Id in Angular 6
Regex Select All Text Between Tags
Angular 5, Html, Boolean on Checkbox Is Checked
Align Left and Right in Mat-Card-Title
How to Stop Background from Jumping to the Top on Modal Toggle
Vertically Align Text Next to an Image
How to Display Raw HTML Code on an HTML Page
Should I Make HTML Anchors With 'Name' or 'Id'
Vertically Align an Image Inside a Div With Responsive Height
How to Avoid Decimal Values in Input Type Number
Setting a Max Character Length in CSS
Select Country Dropdown in HTML Page
How to Vertically Align Text in Input Type="Text"
Fixed Headers on Scroll Inst Working Correctly in Angular Application
Align the Radio Buttons on the Center Whatever the Text Length
Understanding CSS Selector Priority/Specificity
How to Nest a ≪Button≫ Element Inside an ≪A≫ Using Html5