Angular 17: Update a property (that is a component) from a ComponentPortal

Discussão em 'Angular' iniciado por Jacobo, Novembro 10, 2024.

  1. Jacobo

    Jacobo Guest

    I have an existing component called MyGeneralComponent. Now, I need to have some extra content inside that MyGeneralComponent, but in order to separate the logic, and still maintain all the contents and updates made to MyGeneralComponent, I decided to create a new MyPersonalizedComponent that has a CdkPortalOutlet to show MyGeneralComponent.

    export class MyPersonalizedComponent implements OnInit, AfterViewInit {
    @ViewChild(CdkPortalOutlet, { static: true }) portalOutlet!: CdkPortalOutlet;

    ngOnInit(): void {
    this.childPortal = new ComponentPortal(MyGeneralComponent);
    }

    ngAfterViewInit(): void {
    if (!this.portalOutlet.hasAttached()) {
    this.portalOutlet.attach(this.childPortal);
    }

    const attachedRef = this.portalOutlet.attachedRef;
    if (attachedRef === undefined || !(attachedRef instanceof ComponentRef)) {
    return;
    }

    attachedRef.instance.myCustomContent = MyCustomComponent;

    this.navigationParams$ = attachedRef.instance.navigationParameters$;
    this.visible$ = this.navigationParams$.pipe(
    map(params => params.myParam !== undefined)
    );
    this.visible$.subscribe((isVisible) => {
    attachedRef.instance.myCustomContent.visible = isVisible;
    });
    }
    }


    The problem is that, now, I need to insert, in a very specific position of the MyGeneralComponent some other content. Lets called this MyCustomContent.

    Thus inside MyCustomContent I added a new property.

    export class MyGeneralComponent implements OnInit {
    @Input() myCustomContent?: Type<object>;
    }


    and I render it in the following way:

    @if (myCustomContent) {
    <div class="col-span-12">
    <ng-container *ngComponentOutlet="myCustomContent"></ng-container>
    </div>
    }


    However, when I try to update the visible input in my custom component, by subscribing to the visible$ property, I can see it has the right value, but for some reason the attachedRef.instance.parentComponent.visible property is undefined.

    export class MyCustomComponent {
    private _visible: boolean = false;

    @Input() set visible(value: boolean) {
    this._visible = value;
    console.log("Visibility set to:", this._visible);
    }
    get visible(): boolean {
    return this._visible;
    }
    }

    // my-component.component.html
    @if (visible) {
    <p>I'm Visible</p>
    }


    I'm not sure If I'm using the wrong approach for my problem or if I'm doing something wrong here. I recall that in one of my attempts, I was able to see the console.log("Visibility set to:", this._visible); being printed, but nothing being rendered at all.

    Continue reading...

Compartilhe esta Página