Home > Software engineering >  INPUT DATE VALUE ANGULAR
INPUT DATE VALUE ANGULAR

Time:01-30

How can I take the date value in my function "add"? In my function add I have 3 field (name, surname and date), when I call my function add on a button I use (ngSubmit)="add(name.value, surname.value, date...?). What I have to use? Value is for string, I can't find something for Date! This part is on component.html Can you explain me how it works? My input is type="date"

CodePudding user response:

If you don´t have a "date-Picker" or similar in the HTML, and your function "add" needs a date inside in order to work fine (and you think that current date would serve to your purpose), you just symple could do something like this:

HTML

(ngSubmit)="add(name.value, surname.value)"  // Don't put the third parameter

TS "add" function:

add(name: string, surname: string, date:Date = new Date()) // make third parameter as optional, and if you don't give in the HTML, it woul get the actual date

NOTE: If this don't work, you shoul add the code of your "add" function, because maybe it treat the date as a string instead a Date...

CodePudding user response:

I would suggest you use ngForm. This is the easiest for handling this scenario.

See here the Documentation: https://angular.io/api/forms/NgForm

Here is a working example i did: https://stackblitz.com/edit/angular-ivy-pqgewm?devtoolsheight=33&file=src/app/app.component.html

In Essence you want your HTML look like this:

<form #form="ngForm" (ngSubmit)="userService.submitForm(form)">
  <div>
    <label for="firstName">First Name</label>
    <input name="firstName" id="firstName" type="text" ngModel required />
  </div>
  <div>
    <label for="lastName">Last Name</label>
    <input name="lastName" id="lastName" ngModel type="text" required />
  </div>
  <div>
    <label for="dateOfBirth">Date of Birth</label>
    <input name="dateOfBirth" id="dateOfBirth" ngModel type="date" required />
  </div>
  <br />
  <button type="submit">Submit</button>
</form>

And your Submit function to look like this:

submitForm(form: NgForm) {
    if (form.valid) {
      const user: User = {
        name: form.value['firstName'],
        surname: form.value['lastName'],
        birth: new Date(form.value['dateOfBirth']),
      };
    }
  }
  •  Tags:  
  • Related