1

I am using Angular and material datepicker with Reactive Forms and moment MomentDateModule. How can I get the value from the form that is typed by the keyboard?

Here is a small example. If I am typing the correct date, then valueChanges is emitted with correct moment object and everything is ok. With invalid date there is null in this.date.value control

Is there a way to store current input value in Form Control with Reactive Forms? I also tried to add (input)="onInput($event)" to datepicker <input />

onInput(event) { this.date.setValue(moment(event.target.value)) }

But it didn't work. Because datepicker converts invalid moment objects to empty strings for the input value

1 Answer 1

0

If I got you right, you can do it using inputs' value like this.

Your declaration: @ViewChild('input', { static: false }) input: ElementRef

Usage: this.input.nativeElement.value

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

4 Comments

Yes, I can, but the problem is that I have a dynamic form with different control types. So I can have multiple datepickers on the page with other controls.I am handling their values in the container component with this.form.get(control.key).value. With the described approach,I need: 1) store somewhere in the service current values of all datepickers 2) add if for container component and check there if it is datepicker or not, then get value from the service and transform it to moment object. and so on... I hoped that there is some better way to store invalid dates as moment obj in form
Ok, I understand, then of course it's not an option. What kind of "invalid date" do you need to handle? What kind of input?
I have datepicker. User can type there anything he wants. So "my_string" is not a valid date. And if you type "my_string" into mat-datepicker and then try to get the value of the datepicker like this.forms[control.key].value you will get null The main workflow is: 1) user type in the input 2) blur this input 3) input value going to the store from this.forms[control.key].value 4) Then it go back to the datepicker value. As i wrote above in case input value is "my_string" then this.forms[control.key].value === null What we got in this case is empty input after blur
@mr__brainwash sorry for late response. You comment above relates to date adapter issue, material datepicker is using - it's momentjs date adapter by default. Have you tried to override this MomentDateAdapter or maybe create your own one, which is based on momenjs, but maybe storing initial input in some custom field?

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.