【问题标题】:Checkbox filtering only works on refresh Angular2复选框过滤仅适用于刷新 Angular2
【发布时间】:2016-08-29 12:45:11
【问题描述】:

所以为了方便使用,我想添加复选框作为过滤器。但是,它仅在我刷新页面时加载。

这些是我的文件:

文件名.component.ts

import { Component } from '@angular/core';
import { CheckboxFilterPipe } from './checkbox-filter.pipe';

@Component({
    templateUrl: 'app/filename.component.html',
    pipes: [CheckboxFilterPipe]
})

export class filenameComponent {
    checkboxes: any[] = [{
        id: 1,
        label: 'Filter 1',
        state: true
    }, {
        id: 2,
        label: 'Filter 2',
        state: true
    }];

    displayData: any[] = [
        // Objects I want to display
    ];
}

checkbox-filter.pipe.ts

import { Pipe, Pipetransform } from '@angular/core';

@Pipe({
    name: 'CheckboxFilter'
})

export class CheckboxFilterPipe implements PipeTransform {
    transform(values: any[], args: string[]): boolean {
        console.log(args);
        return values.filter(value=> {
            // My filtercode, return true for now
            return true;
        });
    }
}

文件名.component.html

<div class="content-wrapper">
    <div class="row">
        <label *ngFor="let cb of checkboxes">
            <input type="checkbox" [(ngModel)]="cb.state"> {{cb.label}}
        </label>
    </div>
</div>
<table>
    <tr *ngFor="let value of displayData | CheckboxFilter:checkboxes">
        <td>{{ value.value1 }}</td>
        <td>{{ value.value2 }}</td>
        <td>{{ value.value2 }}</td>
    </tr>
</table>

我正在使用 Angular2.rc.0。为了清楚起见,我在这个问题中重命名了我的变量。控制台中的输出仅在我刷新页面时发生,而不是在我(取消)选中复选框时发生。感谢您为解决此问题提供任何帮助。

【问题讨论】:

    标签: javascript angular angular2-pipe


    【解决方案1】:

    Angulars 更改检测不检查对象的内容,只检查对象自身,因此 Angular 无法识别 checkboxes 中更新的 state 并且只要依赖值没有更改,Angular 就不会t 再次调用管道。

    解决方法可以使管道不纯:

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

    这样 Angular 每次运行更改检测时都会调用管道,这种情况很常见,因此这可能会变得很昂贵。

    或者,您可以通过创建数组的副本让 Angular 识别更改

    <input type="checkbox" [(ngModel)]="cb.state"
        (ngModelChange)="forceUpdateCheckboxes()"> {{cb.label}}
    

    forceUpdateCheckboxes() { this.checkboxes = this.checkboxes.slice(); }

    Plunker example

    【讨论】:

    • Angular2 大神来拯救!再次感谢!我选择了第二种解决方案:)
    猜你喜欢
    • 2017-12-30
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2013-01-28
    • 2013-11-03
    • 1970-01-01
    相关资源
    最近更新 更多