2016-08-17 58 views
2

我有以下的HTML代碼:Angular 2:如何隱藏按鈕* ngFor的選擇性迭代?

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

和相應的點擊事件在我的打字稿followproduct.component.ts:

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

一旦點擊一個產品的跟蹤按鈕,其他產品的所有按鈕在迭代中被隱藏 - 這也是顯而易見的,因爲我正在爲迭代按鈕標籤分配隱藏選項。

有沒有什麼辦法隱藏,更新或更改只有選擇性迭代* ngFor的按鈕?

回答

4

使隱藏按鈕成爲一個數組。事情是這樣的

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

而在你的控制器

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

不,這在我的代碼中不起作用。事實上,它會完全停止顯示其他迭代。 –

+1

我編輯了示例ngFor演示以滿足您的需求。作爲我的代碼上面但我必須改變isHidden從任何到任何[]。 http://plnkr.co/edit/E00kPmnzKb7Lql4iWa26?p=preview – garethb

+0

感謝您的編輯。我的代碼現在正在工作。 –

0

給你的按鈕一個ID(你應該做什麼)並使用它。

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

和Controller

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

類似的東西應該工作

更新

對不起,我從來沒有使用過Angular2或打字稿之前,所以我不知道的語法。也許它是這樣的。

+0

_hidebutton ===按鈕{{product.Id}} _:看來這句法離子2,並沒有在我的HTML工作。你有其他語法嗎? –

3

這是因爲所有的產品份額相同的變量命名hidebutton。你所要做的就是,爲每個產品一個新的變量,如下圖所示,什麼

<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;  
    } 
} 
+0

您能告訴我產品,隱藏按鈕,標誌和product.hiddenbutton是如何關聯的,我無法確定流程。 –

+0

您爲每個產品對象動態創建一個名爲**。hiddenbutton **的產品對象屬性。 ** Flag **只是一個接收值的參數變量,您可以使用任何其他名稱。 – micronyks

+0

看我用相關的名字更新了我的答案。 – micronyks