How to leverage Angular Signals for toggling visibility of my components

Discussão em 'Angular' iniciado por Sam, Janeiro 13, 2025.

  1. Sam

    Sam Guest

    I know that Angular Signals could be used in this particular case in order to avoid calling the isVisible function constantly. But I have no experience with this new feature and I cannot figure out what to change in my code to take advantage of Signals. I pasted a simplified snippet of my code below, just for the general idea.

    What should I change to make this work with Signals ?

    visibleSections = [];
    sectionConfig = [
    {
    name: 'someComponent',
    hidden: false
    },
    {
    name: 'otherComponent',
    hidden: false
    }
    ];


    ngOnInit() {
    this.visibleSections = this.sectionConfig.filter(c => !c.hidden);
    }

    public isVisible(section): boolean {
    return this.visibleSections.findIndex(s => s.name === section) > -1;
    }

    public setSectionVisibility(e: any): void {
    this.sectionConfig.find(c => c.name === e.itemValue.name).hidden = e.value.findIndex(p => p === e.itemValue) === -1;
    }


    HTML :

    <p-multiSelect
    #multiselect
    defaultLabel="Show/hide sections"
    optionLabel="title"
    name="show-hide-sections"
    scrollHeight="300px"
    styleClass="multiselect-as-button mr-3 ml-3"
    dropdownIcon="fas fa-bars rotate-90"
    [options]="sectionConfig"
    [(ngModel)]="visibleSections"
    [displaySelectedLabel]="false"
    (onChange)="setSectionVisibility($event)"
    [style]="{ width: '208px' }"
    [showHeader]="false"
    [appendTo]="'body'"></p-multiSelect>


    @if (isVisible("someComponent")) {
    <some-component></some-component>
    }

    @if (isVisible("otherComponent")) {
    <other-component></other-component>
    }

    Continue reading...

Compartilhe esta Página