Adding a new html element using angular template
In Angular, you can add a new HTML element to a template using the following methods:
- *Using the `ngFor
directive**: You can use the
*ngFor` directive to iterate over an array of objects and add a new HTML element for each item in the array.
Example:
<div *ngFor="let item of items">
<p>{{ item.name }}</p>
<button (click)="addItem()">Add new item</button>
</div>
In this example, the *ngFor
directive is used to iterate over the items
array and display each item's name. The addItem()
function is called when the "Add new item" button is clicked, which adds a new item to the array.
- Using the
ng-container
directive: You can use theng-container
directive to add a new HTML element that is not part of the component's template.
Example:
<ng-container *ngIf="showNewElement">
<p>New element added!</p>
</ng-container>
In this example, the ng-container
directive is used to add a new HTML element (<p>New element added!</p>
) only when the showNewElement
variable is true.
- Using the
innerHTML
property: You can use theinnerHTML
property to add a new HTML element to a component's template.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<div [innerHTML]="newElement"></div>
`
})
export class ExampleComponent {
newElement = '<p>New element added!</p>';
addItem() {
this.newElement = '<p>New element added!</p>';
}
}
In this example, the innerHTML
property is used to add a new HTML element (<p>New element added!</p>
) to the component's template. The addItem()
function is called when the "Add new item" button is clicked, which updates the newElement
property with a new HTML element.
- Using the
DOM
property: You can use theDOM
property to add a new HTML element to a component's template.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<div [dom]="newElement"></div>
`
})
export class ExampleComponent {
newElement: any;
addItem() {
this.newElement = document.createElement('p');
this.newElement.textContent = 'New element added!';
}
}
In this example, the DOM
property is used to add a new HTML element (<p>New element added!</p>
) to the component's template. The addItem()
function is called when the "Add new item" button is clicked, which creates a new HTML element using the document.createElement()
method and sets its text content to "New element added!".
Note that the DOM
property is only available in Angular 12 and later versions. In earlier versions, you can use the innerHTML
property instead.