1
votes

How can I show/hide a list item's div depending on which radio button was selected? If I select the first radio button, item[0] should display. If I select the second radio button, item[0] is now hidden and item[1] is showing. I'm not sure what is the best practice to make this work as I already have an *ngFor and you can't combine that with an *ngIf. :( Setting a boolean var inside a component just seems to toggle the whole section which is not what i'm looking for.

HTML

<section>
    <ul>
        <li>
            <input [(ngModel)]="regionSelected" type="radio" id="radio">
            <label>Europe</label>
        </li>
        <li>
            <input [(ngModel)]="regionSelected" type="radio" id="radio">
            <label>USA</label>
        </li>
    </ul>
</section>

<section *ngIf="regionSelected">
    <div *ngFor="let item of result; let i=index" [ngClass]="{'europe': i === 0, 'usa': i === 1}">
        <h3>{{item.title}}</h3>
    </div>
</section>

Any ideas?

2

2 Answers

1
votes

Something like this maybe?

Method in component:

getRadioIndex(regionSelected: string){
    if(regionSelected === 'Europe'){
        return 0;
    }
    if(regionSelected === 'Europe'){
        return 1;
    }
}

Template:

<section *ngIf="regionSelected">
    <span *ngFor="let item of result; let i=index">
        <div *ngIf="i === getRadioIndex(regionSelected)" [ngClass]="{'europe': i === 0, 'usa': i === 1}">
            <h3>{{item.title}}</h3>
        </div>
    </span>
</section>
0
votes
<div>    
    <section>
        <ul>
            <li>
                <input [(ngModel)]="regionSelected" type="radio" id="radio">
                <label>Europe</label>
            </li>
            <li>
                <input [(ngModel)]="regionSelected" type="radio" id="radio">
                <label>USA</label>
            </li>
        </ul>
    </section>

    <section *ngIf="regionSelected">
        <div *ngFor="let item of result; let i=index" 
             [ngClass]="{'europe': i === 0, 'usa': i === 1}" 
             *ngIf="i === regionSelected">
            <h3>{{item.title}}</h3>
        </div>
    </section>

</div>