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


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?

    placeholder="Eintrag hinzuf├╝gen"

    placeholder="Faelligkeitsdatum hinzuf├╝gen"

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


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>
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.