0

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:
enter image description here

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

@mathiaF You dont need to do anything on html side
You don't need to do anything on html side as @Manzurul mentioned. I updated the answer with an example url
Thank you very much for your answer. However, this does not always work. Even if it's a good start, I'm displaying something:)
yup, there's something you need to do in your regex. :) The answer that I provided is solving the part which updating form value only.
Yes, that's exactly it. But it's good thanks to you it works well, I just can't get rid of the slash yet. But it's not much, I think.
1

Remove the subscription and try this:
HTML:

<input .... #birthday (input)="birthday.value=changeValue(birthday.value)" ....>

Typescript:

changeValue(value){
  const resLength = value.length;
  if(resLength < 6 ) {
    return value.replace(/(..)/g, '$1/');
  }
  return value;
}

2 Comments

Thank you very much for your answer, for the moment it doesn't work but I'm almost there with your solution. Thank you
I'll try to put it on plunker:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.