2017-05-09 49 views
2

我有一個簡單管:角2:在管道中的concat陣列而不丟失數據綁定

export class MergePipe implements PipeTransform { 
transform(first: any[], second: any[], order: Boolean): any { 
    return order ? first.concat(second):second.concat(first); 
} 

我使用一個簡單的按鈕,其中:<button *ngFor="let item of items | sort:suffix | filter:filterargs | merge:newItems:false"></button>

然後用newItems.push(值)將一些值推入newItems,但沒有任何反應。如果我從* ngFor中刪除管道,我會收到預期的更改。

我想我對數據綁定的工作方式有些誤解。

感謝您提供任何有用的信息。

+0

純管道只在更改'指針'時更新,例如你的'第一個'換成另一個數組,而不能自己改變。你可以通過設置@Pipp({pure:false})來改變不純的管道。您可以搜索管道文件。 –

+0

感謝您的回答。用不純的管子可以正常工作,但是現在還不能真正理解它是如何工作的。 – Draftsman

回答

3

如果修改其中一個數組,Angulars更改檢測將不會看到更改,因此不會調用管道。
角度更改檢測僅檢查對象標識,但不檢查對象內容。

您可以使管道不純,或者您可以在每次修改後爲Angular創建一個管道副本以查看新陣列。

@Pipe({ name: '...', pure: false}) 

這會導致嚴重的性能問題,因爲現在每次運行更改檢測時都會調用管道。

someMethod() { 
    this.newItems.push(someNewItem); 
    this.newItems = this.newItems.slice(); 
} 

修改後創建副本會導致角度更改檢測識別更改並調用管道。

另一種方法是使用虛擬參數;

counter:int = 0; 
someMethod() { 
    this.newItems.push(someNewItem); 
    this.counter++; 
} 
<button *ngFor="let item of items | sort:suffix | filter:filterargs | merge:newItems:false:counter"></button> 

這樣變化檢測將檢測參數的變化,並調用管道。

+0

非常感謝你,完美的回答,特別是第二個解決方案是一個很好的解決方法。 – Draftsman

+0

不客氣。很高興聽到它適合你:) –

0

看起來像Angular不知道如果數組引用沒有改變重新評估管道。

如果我們看一下他們的管道的討論:

You add the hero into the heroes array. The reference to the array hasn't changed. It's the same array. That's all Angular cares about. From its perspective, same array, no change, no display update.

https://angular.io/docs/ts/latest/guide/pipes.html

你應該把這個代碼,而不是:

newItems = newItems.concat(values)

將更新的參考和原因管道將被重新評估。