Can't modify inner content of ViewContainerRef, only adding tags after it in Angular

Discussão em 'Angular' iniciado por Konrad Viltersten, Dezembro 15, 2024.

  1. I have a few DIVs that may be marked with a directive special. That directive has certain logic that works. Now, I'd like to add a component within the DIV that is equiped with the directive.

    <div special ...>Monkey</div>
    <div regular ...>Donkey</div>


    Following the docs on Using ViewContainerRef (suggested by this answer to a similar issue), I run the following in my directive.

    @Directive({ selector: "[special]" })
    export class SpecialDirective {

    private viewRef = inject(ViewContainerRef); ...
    constructor() {
    const icon = this.viewRef.createComponent(IconComponent);
    }


    It works just as described in the docs: the created icon (corresponding to LeafContent) is placed in the DOM right after the DIV that's marked as special (corresponding to InnerItem). And this is precisely my problem: I want the icon to be a part of the inner HTML of the DIV that's governed by the directive.

    I can't move the directive inwards for various reasons related to its logic. I've tried to access viewRef.element and inspected other fields and methods of it. To no avail. Setting index on the creation didn't help. The closest I got was detaching/inserting from the docs but it only let me manage the order of elements after my DIV, not within it.

    I've seen this answer, but it's not going to help in my case because the alteration is happening after the user clicks on the DIV way past it's been created and placed in the view.

    How can I alter the inside of the viewRef instance? Optimally, I'd like to remove some tags inside it as well besides amending the icon.

    Continue reading...

Compartilhe esta Página