1.你好。有很多关于如何显示/隐藏元素的答案,为迭代数组的每个元素附加一个我们在真/假时更改的属性。
<button (click)="attachmentHide = !attachmentHide"></button>
<itemComp [itemsArray]='item.children' class="col-sm-offset-1 subItemHiden" [class.subItemsShow] = 'showSubItem'></itemComp>
所以每次我们列出数组的每个元素时,它都会创建 item.showSubItem 属性。在这种情况下,我们的数组已更改。
但是,如果我想显示/隐藏这些项目,但不编辑主数组,该怎么办。这很重要,因为我在开始时检查了这个数组是否相等。有创建与数组无关的 var 的答案,但是如何为每个元素创建 var 以分别显示/隐藏每个元素?
更新:
<div class="row col-sm-offset-1" *ngFor="let item of itemsArray">
<div class="col-sm-4">
<div class="row assignedItem">
<span class="glyphicon glyphicon-plus-sign " title="sub items" (click)= "showSubItem = !showSubItem"></span>
<div class=" itemName" title="State:{{item.state}},Type: {{item.type}}">{{item.name}}</div>
<!--users component-->
<!--show subItems-->
<itemComp [itemsArray]='item.children' class="col-sm-offset-1 subItemHiden" [class.subItemsShow] = 'showSubItem'></itemComp>
</div>
</div>
ts文件:
export class ItemComponent {
@Input() itemsArray: Array<Object>;
constructor () {}
}
更新2:
我在 home.ts 中用 i=false 初始化了数组:
viewNodes(result) {
setTimeout(() => {
this.myRes = result;
this.showSubItemsArr = this.myRes.content.map(i => false);
this.itemsParentArray = this.myRes.content;
console.log( this.showSubItemsArr );
this.showAssigned = true;
}, 3000);
}
在我将它发送到子组件之后,在 html 中:
<div class="container">
<div class="row">
<!--show item-->
<itemComp [showSubItems]="showSubItemsArr" [itemsArray]='itemsParentArray' ></itemComp>
</div>
比我尝试使用 showSubItems[idx] 查看项目。
<div class="row col-sm-offset-1" *ngFor="let item of itemsArray let idx=index">
<div class="col-sm-4">
<div class="row assignedItem">
<span class="glyphicon glyphicon-plus-sign " title="sub items" (click)= "showSubItem = !showSubItem"></span>
<span class="glyphicon glyphicon-paperclip" title="attached docs" (click)="attachmentHide = !attachmentHide"></span>
<div class=" itemName" title="State:{{item.state}},Type: {{item.type}}">{{item.name}}</div>
<!--users component-->
<usersComp [userArray]="item.assignment"></usersComp>
</div> {{showSubItems}}
<!--attachment component-->
<attachmentComp class="col-sm-offset-1" [attachmentsArray]='item.attachments' *ngIf="attachmentHide"></attachmentComp>
<!--show subItems-->
<itemComp [itemsArray]='item.children' class="col-sm-offset-1 subItemHiden" [class.subItemsShow] = 'showSubItems[idx]'></itemComp>
</div>
</div>
但它显示错误:
TypeError:无法读取未定义的属性“0”
但是当我渲染所有{{showSubItems}}
数组时,它显示false,false,false
没有问题。
看起来idx
价值还没有准备好进行第二次迭代。抱歉不能使用 plunker(正在处理它)。