Alexandr
Alexandr

Reputation: 213

Angular2 change detection issue. Input field doesn't update if class field does'n change, but input field value is different

I create simple example: plnkr. Try to enter something like 123qwe in first field. "qwe" doesn't disappear. But if enter a new digit all non-digit characters will disappear.

In second field non-digit characters is replacing by '!' and it field works as expected.

My code:

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      Doesn't work: <input [value]="val | replace:pattern:''" (input)="val=$event.target.value">
      <br>
      Works: <input [value]="val2 | replace:pattern:'!'" (input)="val2=$event.target.value">
    </div>
  `,
  directives: []
})
export class App {
  val: string = "";
  val2: string = "";
  pattern = /[^0-9]/g;
  constructor() {
  }
}

Is there any workaround to make first field work like a second but with replacing with empty string? Is there expected behavior?

Upvotes: 3

Views: 139

Answers (1)

yurzui
yurzui

Reputation: 214017

Just try it:

@Pipe({name: 'wrappedPipe'})
class WrappedPipe implements PipeTransform {
  transform(value) { return WrappedValue.wrap(value); }
}

<input [value]="val | replace:pattern:'' | wrappedPipe" (input)="val=$event.target.value">

In this case it will work as you can see in the picture below

enter image description here

See working plunkr https://plnkr.co/edit/p6gTqn3sMQqOuxL2bsuS?p=preview

pattern:'' doesn't work because it returns always the same result

1234qwe    => 1234
1234qwerty => 1234
1234qwerty1 => 12341 // changes

Upvotes: 3

Related Questions