[FIXED] How do I make an Input required in Typescript?

Issue

I have two Inputs, that have to be required, in order to use the "Add"-Button or I was thinking to use *ngIf to make the button visible or not, but it doesnt work. Whats wrong?

<input
    #neueEintragBeschreibung
    placeholder="Eintrag hinzuf├╝gen"
    class="lg-text-input"
  />

  <input
    #neuesEintragFaelligkeitsdatum
    placeholder="Faelligkeitsdatum hinzuf├╝gen"
    class="lg-text-input"
  />

  <div *ngIf="neueEintragBeschreibung.value">
  <button class="btn-primary" (click)="addEintrag(neueEintragBeschreibung.value, neuesEintragFaelligkeitsdatum.value)">
    Add</button>
  </div>

Solution

You’re not supposed to access input.value this way. You should use the forms API to do so. E.g:

<form #form="ngForm" (ngSubmit)="handleSubmit(form)">
  <input type="text" required name="myField" ngModel />

  <ng-container *ngIf="form.valid">
    <button type="submit">Add</button>
  </ng-container>
</form>
handleSubmit(form: NgForm) {
  console.log(`You entered: ${form.value.myField}`);
}

What’s happening here:

  1. You create a form with one field, called "myField".
  2. You make "myField" required by using the required attribute.
  3. You render the "Add" button only when the form is valid. Since the form has a required field, it will only be valid once this field is filled by the user.

Remember to add FormsModule to your module’s imports.

Answered By – Allan Juan

Answer Checked By – Timothy Miller (FixeMe Admin)

Leave a Reply

Your email address will not be published.