Reputation: 37
for a project I need to add buttons programmatically via ngOnChanges
in renderer2
. I tried it with ElementRef
in constructor
, as @ViewChild
and with direct, unsafe, inserting, but there is no button showing up. I need to react on text as @Input
, that's why I need to do it in ngOnChanges
(if there is a working other way I will accept it). I'm working with Angular/Node 12 and TypeScript 4.
My ngAfterViewInit()
is empty.
I worked on a tiny example project, so I can share this little code snippet:
HTML:
<div class="wrapper">
<div [innerHTML]="html" id="html-wrap" #htmlWrap></div>
</div>
constructor
:
@ViewChild('htmlWrap', { static: false })
public htmlWrap!: ElementRef<HTMLElement>;
constructor(private renderer: Renderer2,
private elementRef: ElementRef) { }
// elementRef is not used in this example
ngOnChanges()
-Method:
ngOnChanges(changes: SimpleChanges) {
for (const propName in changes) {
// did something with text for innerHTML
const pres = document.querySelectorAll('pre');
if (!pres) return;
pres.forEach((pre: HTMLElement) => {
const buttonWrapper = this.addButtons();
this.renderer.appendChild(pre, buttonWrapper);
this.renderer.appendChild(this.htmlWrap.nativeElement, pre)
});
}
}
addButtons()
-Method:
private addButtons(): HTMLElement | null {
const wrapper = this.renderer.createElement('div');
if (!wrapper)
return null;
// create buttons via this.renderer.createElement("button");
// same with texts
this.renderer.appendChild(button1, text1);
// add button event
this.renderer.appendChild(wrapper, button);
return wrapper;
}
Edit: forgot to mention @ViewChild. Sorry.
Upvotes: 1
Views: 29