0

I am using an HTML form in my Angular project, but it keeps ignoring the "value" and "selected" parameters. For the first case, I am trying to set the current timestamp as a default value for a datetime-local field.

The HTML code :

<div class="form-group">
  <label for="timestamp_honeycomb">Date :</label>
  <input type="datetime-local" class="form-control" id="timestamp_honeycomb" formControlName="timestamp_honeycomb" value="{{ timeElapsed | date: 'yyyy-MM-ddTHH:mm' }}" />
</div>

<div class="form-group">
  <label for="smell_beehive">Odeur de la ruche</label>
  <select name="smell_beehive" class="form-select-sm" id="smell_beehive" formControlName="smell_beehive">
    <option value="faible" selected="selected">Faible</option>
    <option value="moyenne">Moyenne</option>
    <option value="forte">Forte</option>
  </select>
</div>

The .ts code of the form :

formGroup = this.formBuilder.group({
    timestamp_honeycomb: new FormControl([Validators.required]),
smell_beehive: new FormControl([Validators.required, Validators.pattern(this.regex)]),
)}

Thank you in advance. EDIT : The "selected" part is solved, as I used this format :

smell_beehive: new FormControl('faible',[Validators.required, Validators.pattern(this.regex)])

Yet I remain curious about how to set a default value via the html view.

  • 1
    You can pass a default value to `FormControl()` – Harun Yilmaz Apr 06 '22 at 09:01
  • I know but it doesn't work, for the timestamp. Typescript seems to have no proper wait to format the current date in the right format, for the datetime-local field. – Captain Harlock Apr 06 '22 at 09:07
  • you'r not supposed to add `new FormControl` inside `FormBuilder` just add it like this: `timestamp_honeycomb: ['', Validators.required]` – Eli Porush Apr 06 '22 at 09:38
  • It doesn't seem to read the value parameter of the input field that way either. Btw, I read some tutorials showing *new FormControl* inside *FormBuilder*, and it always worked that way. Is it bad/deprecated ? – Captain Harlock Apr 06 '22 at 09:47

1 Answers1

0

I found a way here : https://stackoverflow.com/a/51395993/9522006

Following that method, I then wrote my variables this way :

  timeElapsed = Date.now();
  formTime = this.datepipe.transform(this.timeElapsed, 'yyyy-MM-ddTHH:mm');

And, in the form declaration :

 timestamp_honeycomb: new FormControl(this.formTime, [Validators.required])