Stefan Norberg
Stefan Norberg

Reputation: 1225

Angular 14: Create dynamic component in dynamic HTML?

I am converting a component's @Input into MathML. MathML supports embedding HTML, and I would like to inject/create a live angular component (a component wrapping an input field) inside the generated MathML at a specific place.

I'm doing something like this: this.elementRef.nativeElement.innerHTML = toMathML(this.math)

I have tried to add <div #replaceme></div> inside the MathML and then picking up the ViewContainerRef with @ViewChild, but that doesn't seem to work. ViewChild is always undefined. When I place the #replaceme in the component's template the ViewChild contains a ViewContainerRef.

I am aware of https://github.com/angular/angular/issues/44660

Is there another way to inject a ViewContainerRef#createComponent() at a specific place without disabling AOT?

@Component({
    selector: 'mathstuff',
    template: ``
})
export class DynComponent implements OnInit, AfterViewInit {
    @ViewChild('replaceme', {read: ViewContainerRef}) dynEl: ViewContainerRef;

    constructor(private elementRef: ElementRef) {
    }

    ngOnInit(): void {
        this.elementRef.nativeElement.innerHTML = '<h1>dynamic</h1><div #replaceme></div><h1>end dynamic</h1>';
    }

    ngAfterViewInit() {
        console.log(this.dynEl);
        this.dynEl?.createComponent(MyInputComponent);
    }
}

Upvotes: 1

Views: 570

Answers (0)

Related Questions