D
D
Deodatuss2016-03-31 15:45:10
JavaScript
Deodatuss, 2016-03-31 15:45:10

Why doesn't Pipe work correctly in Angular2?

The task is simple, it is necessary that only numbers and only less than a certain number are entered into the input. I did it like this:

export class MaxNumber implements PipeTransform{
   transform(value, [maxNumber]) {
        value = value.replace(/[^\d]+/g,'');
        value = value > maxNumber?maxNumber:value;
        return value;
    }
}

Well, then in the template I called something like this:
<input type="text" [ngModel]="obj.count | maxNumber:1000" (ngModelChange)="obj.count=$event" />

But it works very strangetyts .
There is something I really don't understand. I would be grateful if someone could explain why this is happening.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-05-15
@Deodatuss

Update angular2 final release:
There is an easier way to achieve the same behavior:

import {Pipe, PipeTransform, WrappedValue} from '@angular/core';
@Pipe({ name: 'maxNumber'})
export class MaxNumber implements PipeTransform{
  transform(value, maxNumber) {
    value = value.replace(/[^\d]+/g,'');
    return WrappedValue.wrap(value > maxNumber ? maxNumber : value);
  }
}

This is due to an interesting change trapping mechanism implemented in angular2.
The best way to find out how change detection works is through the debugger. The update works on the principle of comparing two data branches:
Comparison occurs by the method of one interesting looseNotIdentical function
// JS has NaN !== NaN
export function looseIdentical(a, b): boolean {
  return a === b || typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b);
}

And the whole update starts below like this
There are more nuances with pure/impure.
The output is something like this:
1) maxNumber does not change, which means we do not expect any changes in this branch (the changes variable remains null)
2) transform() returns either a number up to 1000 or 1000. And as soon as it starts returning 1000, then in picture 2 "1000" === "1000" will be compared and no updates will run either (changes will not be recorded either) Related
article How does Angular 2 Change Detection Really Work ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question