2017-02-11 10 views
0

我有一個自定義管道來過濾數組。管道用於子組件內部,通過輸入參數傳遞到子組件的數據。輸入數據更改時,不調用管道。當在子組件內使用ChangeDetectionStrategy.OnPush時,我有什麼不同之處?輸入變化時未調用子組件的管道

編輯

在下面的例子中,產品列表容器會從NGRX店內產品。數據通過輸入參數傳遞到產品列表組件。

在產品列表組件中,我有一個過濾器用於根據某些條件過濾出行。我看到的問題是,當輸入值更改管道功能不被調用。管道在組件加載時只被調用一次。

@Component({ 
    selector: 'product-list-container', 
    template: ` 
    <app-product-list [productList]="productList$ | async"></app-product-list> 
    ` 
}) 
export default class ProductListContainer implements OnInit { 
    public productList$: Observable<Product[]>; 
    constructor(public store: Store<AppState>) { 
    } 
    ngOnInit() { 
    this.productList$ = this.store.select('productList'); 
    } 
} 

@Component({ 
    selector: 'app-product-list', 
    template: ` 
    <div *ngFor="let product of productList | filterActiveProduct"> 
    // More code here 
    </div> 
    `, 
    changeDetection: changeDetectionStrategy.onPush 
}) 
export default class ProductList { 
    @Input() productList: Product[]; 
    constructor() { 
    } 
} 

@Pipe({ 
    name: 'fromNow' 
}) 
export class filterActiveProduct { 
    transform(products: Product[], args: Array<any>): string { 
    return products.findAll(p => p.isActive); 
    } 
} 

感謝,

+0

請包括相關的代碼 - 而不是描述所述碼 - 的問題。 – cartant

+0

@cartant我已經在上面添加了示例代碼。謝謝! – Yousuf

+0

找到了一個潛在的解決方案。如果我在管道上設置了pure:false,當輸入發生變化時它會被調用。 – Yousuf

回答

0

因爲你管Pure pipes

只有當角度檢測到對輸入值的純粹更改時,角才執行純管道。純粹的改變是對原始輸入值(字符串,數字,布爾值,符號)或已更改的對象引用 (日期,數組,函數,對象)的更改。

Angular忽略(複合)對象內的更改。如果我們更改輸入月份,添加到輸入數組或更新輸入對象屬性,它將不會調用 純管道。

使用Impure pipes你的情況:

角執行的每個組件的變化 檢測週期中的不純管。一個不純的管道將被稱爲很多,每次擊鍵或鼠標移動的次數都是如此。

考慮到這個問題,我們必須實施一個不錯的管道,並且很好地保護 。昂貴的,長期運行的管道可能會破壞用戶的體驗。

FilterActiveProduct:

@Pipe({ 
    name: 'filterActiveProduct', 
    pure: false 
}) 
export class FilterActiveProduct {} 

產品列表:

@Component({ 
    selector: 'app-product-list', 
    template: ` 
    <div *ngFor="let product of productList | filterActiveProduct"> 
    // More code here 
    </div> 
    `, 
}) 
export default class ProductList { 
    @Input() productList: Product[]; 
    constructor() { 
    } 
} 

在此之後文檔頁面:https://angular.io/docs/ts/latest/guide/pipes.html

+0

謝謝,使管道不純固定的問題。 – Yousuf