Karan Desai
Karan Desai

Reputation: 3142

Angular 2: How to hide button only on selective iteration of *ngFor?

I have following HTML code:

<table>
<tr *ngFor='let product of products'>
     <td>
            <button [hidden]="hidebutton" (click)="Follow(product.Id)">Follow</button>                           
     </td>
</tr>
</table>

And corresponding click event in my Typescript followproduct.component.ts:

@Component({
   ---
   ---
})
export class followproduct implements onInit{
hidebutton: boolean = false;
Follow(productId: number) {
        ---
        this.hidebutton = true;      
    }
}

Upon clicking on Follow button of one product, all the buttons of other product in iteration gets hidden-and that's obvious too, as I am allotting the hidden option to iterative button tag.

Is there any way to hide, update or change the button of only selective iteration of *ngFor?

Upvotes: 2

Views: 1805

Answers (3)

garethb
garethb

Reputation: 4041

Make hidebutton an array. Something like this

<table>
    <tr *ngFor='let product of products'>
        <td>
            <button [hidden]="hidebutton[product.Id]" (click)="Follow(product.Id)">Follow</button>                           
        </td>
    </tr>
</table>

And in your controller

@Component({
   ---
   ---
})
export class followproduct implements onInit{
hidebutton: any[] = [];
Follow(productId: number) {
        ---
        this.hidebutton[productId] = true;      
    }
}

Upvotes: 5

Herr Derb
Herr Derb

Reputation: 5357

give your buttons an id (what you should do anyway) and use that.

<tr *ngFor='let product of products'>
     <td>
            <button [hidden]="hidebutton==='button'+product.Id" (click)="Follow(product.Id)">Follow</button>                           
     </td>
</tr>

And in the controller

@Component({
   ---
   ---
})
export class followproduct implements onInit{
hidebutton: string= '';
Follow(productId: number) {
        ---
        this.hidebutton = 'button'+product.Id;      
    }
}

Something like that should work

Update

Sorry I never used Angular2 or typescript before, so I'm not aware of the syntax. Maybe it works like this.

Upvotes: 0

micronyks
micronyks

Reputation: 55443

That's because all product share same variable named hidebutton. What you have to do is, create a new variable for each product as shown below,

<tr *ngFor='let product of products'>
     <td>
            <button [hidden]="product.hidebutton"                           
           (click)="Follow(product.Id,product.hiddenbutton)">Follow</button>                           
     </td>
</tr>

export class followproduct implements onInit{
//hidebutton: boolean = false;
Follow(productId: number,hidebutton:boolean) {
        ---

        //if(hidebutton==false)

        hidebutton= true;

        //hidebutton =!hidebutton;    
    }
}

Upvotes: 3

Related Questions