2017-07-18 67 views
2

我正在使用angular2應用程序。在我的要求是使用數組創建多個複選框,並選中最後一個複選框,以顯示div,如果最後一個複選框未選中,請隱藏div。如果在angular2中選中/取消選中最後一個複選框,如何顯示/隱藏div?

Component.ts: -

peoples: any = [ 
{ "name":"rahul", "status":false}, 
{ "name":"rija", "status":false}, 
{ "name":"roy", "status":false}, 
{ "name":"ninja", "status":false}, 
{ "name":"riya", "status":false}, 
{ "name":"rohit", "status":true}, 
]; 

component.html

<div *ngFor = "let people of peoples"> 
    <input type = "checkbox" [value] = 'people?.name' [checked] = "people?.status"> 
     {{people?.name}} 
    </div> 

/****** Hide/show div (if last checkbox is checked so show is div and unchecked so hide this div ******/ 
<div> 
    <span> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span> 
</div> 
+0

嘗試'和'* ngFor' –

+0

last'指數與'* ngFor'像'* ngFor = 「;讓最後=最後讓人民的人」 使用它。你將從這裏得到ngFor的最後一個索引,你可以用它來檢查複選框是否是最後一個 –

+0

@harleen,或者你也可以使用這個'[hidden] =「!peoples [peoples.length - 1] .status」' –

回答

0

就像pardeep傑恩指出,你可以使用

[hidden]="!peoples[peoples.length - 1].status" 

但我只想提,然後用ngModel,並使用,你也可以擺脫時[checked]當使用。 `

<div *ngFor="let people of peoples"> 
    <input type="checkbox" [value]="people.name" [(ngModel)]="people.status"> 
    {{people?.name}} 
</div> 


<div [hidden]="peoples[peoples.length - 1].status"> 
    <span> Lorem Ipsum is simply dummy text </span> 
</div> 
1

你可以這樣做:

<!-- Hide/show text here --> 
    <div *ngIf="peoples[peoples?.length - 1]?.status"> 
     <span> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span> 
    </div> 

在上面的代碼示例,如果最後一個元素是checked(如果狀態是true),然後顯示以下div

編輯:

更改HTML爲:

<div *ngFor = "let people of peoples;let i = index;"> 
    <input type = "checkbox" [value] = 'people?.name' [checked] = "people?.status" (change)="cahngeStatus(i)"> 
    {{people?.name}} 
</div> 
<div *ngIf="peoples[5].status"> 
    <span> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span> 
</div> 

添加下面的函數來JS:通過導入FormsModule

cahngeStatus(index) { 
    peoples[index].status = !peoples[index].status; 
} 

我們可以通過使用ngModel或者做希望這有助於:)

+0

這不是工作顯示錯誤: - Component.html:220錯誤TypeError:無法讀取屬性'-1'未定義 –

+0

Peoples數組被定義並且有數據? – SaiUnique

+0

這不起作用。 –

相關問題