问题描述
我正在编写一个只允许使用某些数字格式的组件,除了一件事情外,它工作得很好,它每次都对值进行切片,但每两次仅更新一次视图.因此,如果我按以下顺序编写它:
I'm writing a component that should only allow certain number formats, it works great except for one thing, it slices the value every time but only updates the view every two times. So if I write it in this sequence:
A乙CD
我最终得到BD.
我不明白这里发生了什么.
I can't understand what is happening here.
这是组件:
@Component({
selector: 'my-input',
templateUrl: 'my-input.html',
styleUrls: ['my-input.css'],
inputs: [
'model',
'pattern'
],
host: {
'(input)': 'isNum($event.target.value)'
},
providers: [
RegexService
]
})
export class FormNumberInputComponent {
@Input() model: number;
@Output('modelChange') onModelChange: EventEmitter<any> = new EventEmitter();
constructor(private _regexes: RegexService) {}
isNum(value) {
this.isInvalid = !this._regexes.test(this.pattern || 'integer', value);
if (!this.isInvalid) {
this.onModelChange.emit(value);
}
else {
value = value.slice(0, -1);
// This also doesn't work, gives the same result
value = value.substring(0, -1);
this.onModelChange.emit(value);
}
}
}
简单模板:
<input [(ngModel)]="model">
像这样在父组件中使用它:
Using it from parent component like this:
<my-input [(model)]="myModel1"></my-input>
推荐答案
尝试一下:
this.onModelChange.emit(new String(value));
这里是对应的监听器 https://plnkr.co/edit/2KqCGggSDOdXhjiJEw68?p=preview
我会为此编写而不是组件验证自定义管道: https://plnkr.co/edit/xCvnJ9682lV0Z1sBcK68?p =预览
I would write instead of component validation custom pipe for that: https://plnkr.co/edit/xCvnJ9682lV0Z1sBcK68?p=preview
也许 http://blog.jhades.org/how-does-angular-2-change-detection-really-work/
这篇关于尽管每次都运行,但值仅每两次切片一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!