0

Am trying to create a angular 2 pipe for the array of elements so that it filters the only that elements based on the selected false,

my array

this.states =  [ {name: 'John', selected: false, value: 1}, {name: 'Bill', selected: false, value: 2},
    {name: 'Smith', selected: false, value: 3}, {name: 'Alex', selected: false, value: 4},
    {name: 'Martin', selected: false, value: 5}, {name: 'James', selectes: false, value: 6}];

I need to filter the value which is of selected false,

My Pipe Code

import {Injectable,Pipe} from 'angular2/core';

@Pipe ({
name : 'restrictValues'
})
@Injectable()
export class restrictValues implements PipeTransform {
    transform(items: any[], args: any[]): any {
        return items.filter(item => item.id.indexOf(args[1]) !== true);
    }
}

My HTML Implementation

  <select ngControl="select_state" (change)="statechange()" #select_state="ngForm" class="form-control btn btn-primary">
    <option *ngFor="#statez of states | restrictValues : false" value="{{statez.value}}">
        {{statez.name}}
    </option>
  </select>

The pipes in not working as expected please correct me if any thing is wrong in the code

3 Answers 3

2
@Pipe({
    name:'restrictValues'
})
@Injectable()
export class restrictValues implements PipeTransform {
    transform(items: any[], args: any[]): any {
        return items.filter(item => item.selected === false);
    }
}

Notice how your code sample isn't actually looking at the selected property of your object - it's selecting id.

Sign up to request clarification or add additional context in comments.

1 Comment

am trying to remove the selected options from selected box if its already selected in another select box using angular 2 do you have any idea on that
2

You might need to make the pipe impure

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

otherwise it won't be called when items are added/removed/modified in states.

This causes the pipe to be executed at each change detection cycle. You might consider using an observable that actively notifies about changes.

Also in newer Angular2 version (since ~RC.1) the optional parameters aren't passed as an array anymore

transform(items: any[], args: any[]): any {

should be

transform(items: any[], param1?:any, param2?:any): any {

depending on how many parameters you want to support

Comments

0
import {Injectable,Pipe} from 'angular2/core';

@Pipe ({
name : 'restrictValues'
})
@Injectable()
export class restrictValues implements PipeTransform {
    transform(items: any[], args: any[]): any {
        return items.filter(item => !item.selected);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.