I have created a DOM element using this.document.createElement('h1')
and I want the element to be added to section tag with a template reference variable (myTRF), something like below,
<section>
<h1 #myTRF>This is my heading</h1>
</section>
Is there any way it can be achieved in Angular?
CodePudding user response:
First set some Id to section tag. (h1-section - id for section tag)
var header = document.createElement("H1"); var text = document.createTextNode("This is my heading"); header.appendChild(text); document.getElementById("h1-section").append(header);
CodePudding user response:
You can insert DOM elements into a parent div having template reference variable and access it using @viewchildren : queryList dynamically.
@Component({
selector: 'my-app',
template: `
<div #div>#div is a template variable</div>
`,
})
export class App {
@ViewChildren("div") divs: QueryList<any>
ngAfterViewInit() {
this.divs.forEach(div => console.log(div));
}
}
Reference : https://angular.io/api/core/ViewChildren