仅更新* ngFor数组Angular2中的选定数组项

时间:2017-04-12 21:58:09

标签: arrays angular frontend

我有一个* ngFor循环来显示库。单击库时,该库的类别将显示在树状结构的下方。类别也使用* ngFor循环显示。当我扩展了一个库并单击另一个库时,BOTH库中的类别将更新为刚刚单击的库中的类别。我正在寻找的功能是只更新选定的库类别,并保持其他类别。这里有一篇帖子似乎与我的问题很接近,但我无法让它发挥作用。

Using *ngFor to loop through an array and *ngIf to select which elements from the array to list

这是我的代码:

library.component.html

Control.Monad

library.service

GHCi> :t join @((->) _)
join @((->) _) :: (t -> t -> a) -> t -> a
GHCi> join (*) 5
25

库category.component.html

<div *ngFor="let messageLibrary of onHoldMessageLibraryService.data"  class="library mgn-top10 ft-size14">          
    <a (click)="onHoldMessageLibraryService.getSelectedMessageLibrary(messageLibrary)"><i class="fa fa-folder-o mgn-right10" aria-hidden="true"></i>{{messageLibrary.Name}}</a>
    <library-category *ngIf="messageLibrary.treeIsExpanded" (displayMessagesFromSelectedCategory)="getOnHoldMessages()"></library-category>
</div>

树data.ts

public treeIsExpanded: boolean;
public selectMessages: boolean;
public data: TreeData[];
public selectedName: string;
public selectedValue: number;


public getSelectedMessageLibrary(messageLibrary): void {
     this.selectedMessagesLibrary = messageLibrary;
     this.selectedMessagesLibrary.treeIsExpanded = !this.selectedMessagesLibrary.treeIsExpanded;
   }



public dummyData(): void {
    let myTree: TreeData[] = new Array();
    myTree.push(
    {
      Name: 'Banking Library',
      Id: 1,
      Category: [{
        Name: 'Credit Cards',
        Id: 11,
        Category: null
      }]
     },
    {
      Name: 'Automobile Library',
      Id: 2,
      Category: [{
        Name: 'Cars',
        Id: 12,
        Category: null
      }]
     },
    {
      Name: 'Coffee Library',
      Id: 3,
      Category: [{
        Name: 'Americano',
        Id: 13,
        Category: null
      }]
     }
    )

    this.data = myTree;

   }

}

1 个答案:

答案 0 :(得分:0)

public getSelectedMessageLibrary(messageLibrary): void {
     this.selectedMessagesLibrary = messageLibrary; 
     this.selectedMessagesLibrary.treeIsExpanded = !this.selectedMessagesLibrary.treeIsExpanded; //this line is not giving desired result
   }

替换为

public getSelectedMessageLibrary(messageLibrary): void {
     messageLibrary.treeIsExpanded = !messageLibrary.treeIsExpanded;
   }

如果你将trackBy与NgFor

一起使用会更好