I apologize in advance for my English and hope to make myself understood.
I have a form and I would like the user to add a date in an input, and the /
of I add by myself. The code works very well because it is displayed correctly in the console
. But it is impossible to reproduce this in the input(type = text).
here is the component.ts:
ngOnInit() {
this.changes()
}
changes() {
this.petForm.controls.birthday.valueChanges
.subscribe(res => {
const resLength = res.length
if(resLength < 6 ) {
res.replace(/(..)/g, '$1/')
}
})
}
In the console
no problem here's what it looks like:
Here the template:
<div class="form-group">
<label for="birthday" class="size0">{{ 'PARTNER.bday_placeholder' |
translate}} *</label>
<input
class="input--default input__signup__default"
formControlName="birthday"
type="text"
placeholder="{{'PARTNER.bday_placeholder' | translate}} *"
required>
</div>
I hope I was able to explain my problem and that you were able to understand me. Thank you to those who are trying to solve this small problem.
For reactive form, you cannot just update the value like how you do it. Instead of
res.replace(/(..)/g, '$1/')
Should be:
this.petForm.controls.birthday.setValue(res.replace(/(..)/g, '$1/'), {
emitEvent: false
});
Take note of the setValue
second params, I pass in emitEvent: false
to not trigger value changes event. Else your code might end up infinite loop.
Example url: https://stackblitz.com/edit/angular-amqta3