Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

339
Visualizações
Angular ngModel doesn't update when `ngModelChange` keeps value

I have a text field represented as: field = {text: "", valid: false}, and an input with [(ngModel)]="field.text".

I want to make that field only accept a defined set of characters (for this issue, numbers), and doing (keypress) doesn't work on mobile, so I did: (ngModelChange)="fieldChanged(field)"

The method does the following:

fieldChanged(field) {
    console.log(field.text);
    field.text = Array.from(field.text).filter((char:string) => "0123456789".indexOf(char) != -1).join("");
    console.log(field.text);
}

And it's behaviour is extremely weird.

Legend: - input: what key was pressed - before update: first console.log - after update: second console.log - output: what I see on screen in the input

| input   | before update | after update | output |
|---------|---------------|--------------|--------|
| ""      | ""            | ""           | ""     | <- starting position, no event
| "a"     | "a"           | ""           | "a"    |
| "a"     | "aa"          | ""           | "aa"   |
| "4"     | "aa4"         | "4"          | "4"    |
| "a"     | "4a"          | "4"          | "4a"   |
| "a"     | "4aa"         | "4"          | "4aa"  |
| "4"     | "4aa4"        | "44"         | "44"   |

Why does it always update the output when I enter a legal character? It should be working for each event call.

Edit: Plunker

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I think the cause is that modifying the value on ngModelChange breaks change detection, for example if you change the value back to the previous value, because an invalid character was added.

A workaround:

constructor(private cdRef:ChangeDetectorRef) {}

fieldChanged(field) {
    console.log(field.text);
    field.text = Array.from(field.text).filter((char:string) => "0123456789".indexOf(char) != -1).join("");
    console.log(field.text);
    var tmp = field.text;
    field.text = null; // or some other value that normally won't ever be in `field.text`
    this.cdRef.detectChanges();
    field.text = tmp;
    this.cdRef.detectChanges(); // I guess this 2nd call won't be necessary
}
about 4 years ago · Santiago Trujillo Relatório

0

If anyone having the issues in updating the value, use setTimeout function while updating

// setTimeout function
setTimeout(() => {
  field.text = temp;
  this.cdRef.detectChanges();
}, 1);
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda