简体   繁体   中英

Angular2 ngModel doesn't clear when set to “”

Example class for storing my data

export class Key {
    value: any = '';

    formatter() {
        let value = MyFunction(this.value);

            if(!value) {
                value = '';
            }

            this.value = value;
        }
    }
}

ngModel input field

<input type="text" [(ngModel)]="key.value" (ngModelChange)="key.formatter()">

MyFunction() - Should remove all non-numeric characters from the string and return JUST the numbers

function MyFunction(mystr) {
   mystr = mystr.replace(/\D/g,'');

   if(mystr.length === 0) {
        return "";
   }else {
        return mystr;
   }
}

When MyFunction() returns an empty string and tries to update key.value... Instead of clearing the input field it keeps appending the new letters.

Am I missing something?

In key.formatter() function replace if condition with

if(value === ""){ 
    ... 
}

Hope this helps!!!

代替(ngModelChange)尝试使用[value]="key.value | yourCustomPipe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM