onmyway
onmyway

Reputation: 1515

How set up Angular2 Template Driven form element with two-way binding as well as template driven form validation

How do I correctly set up an Angular template driven form element to have both template driven validation as well as two-way binding? Is it possible?

I have tried a couple different ways of using ngModel, but cannot seem to get two-way binding to work, without some drawback. I am sure I am missing something stupid.

When I use [(ngModel)]="city" as well as well as #city="ngModel" as per example below, I get the following error:

Error: Cannot assign value "$event" to template variable "city". Template variables are read-only.

Element setup:

<div class="form-group col-md-3 mr-3">
  <label
    [class.error-label]="!city1.valid && city1.touched"
    for="city"
    >City or Town*
  </label>
  <input
    type="text"
    id="city"
    ngModel
    name="city"
    required
    #city="ngModel"
    [(ngModel)]="city"
  />
  <span *ngIf="!city.valid && city.touched" class="error-text"
    >Please enter your City or Town</span
  >
</div>

When I do not use [(ngModel)]="city", I am not getting two-way binding. And when I rename my local reference #city="ngModel" to something like #cityWhatever="ngModel", the value for city is undefined when submitting the form:

<form
 (ngSubmit)="onSubmit(personalDetails)"
 #personalDetails="ngForm"
>

I am running Angular version: "@angular/common": "~9.1.11"

Thank you in advance!

Upvotes: 0

Views: 451

Answers (1)

Fateh Mohamed
Fateh Mohamed

Reputation: 21377

try this and remove ngModel

<input
 type="text"
 id="city"
 name="city"
 required
 #city="ngModel"
 [(ngModel)]="model.city"
/>
<span *ngIf="!city.valid && city.touched" class="error-text">
  Please enter your City or Town
</span>

Upvotes: 0

Related Questions