2

for getCities(), i am fetching data from api, which i just showed in li tag, i am in deliama how to submit the check box value,

when customer will check for multiple cities

 <form #hlForm="ngForm" (ngSubmit)="filterData(hlForm)">
   <span>
    <button type="submit" class="btn-blue" (click)="getCities()">Select City</button>
    <ul class="location-filter" *ngIf="cityList">
     <li *ngFor="let city of cityList">
       {{city}} <input type="checkbox" name="selectCity">
     </li>
   </ul>
  </span>
 <button type="submit" value="submit">submit</button>
</form>

3 Answers 3

1

When using template driven forms, add NgModel to the element attributes.

You should also add a unique name to each li element to be able to differentiate between values:

 <li *ngFor="let city of cityList">
   {{city.name}} <input type="checkbox" [name]="city.name" ngModel>
 </li>

Stackblitz demo

Sign up to request clarification or add additional context in comments.

Comments

1

You need to have an array where you can store all your selected cities, and update this array each time a checkbox for a city is checked/unchecked.

Change your code to:

 <form #hlForm="ngForm" (ngSubmit)="filterData(hlForm)">
   <span>
    <button type="submit" class="btn-blue" (click)="getCities()">Select City</button>
    <ul class="location-filter" *ngIf="cityList">
     <li *ngFor="let city of cityList">
       {{city}} <input value={{city}} (change)="onCheckChange($event)" type="checkbox" name="selectCity">
     </li>
   </ul>
  </span>
 <button type="submit" value="submit">submit</button>
</form>

And your onCheckChange method would look like this:

onCheckChange(event: any)
  {
    console.log(event.target.value)
    if (event.target.checked)
    {
      this.selectedCities.push(event.target.value);
    }
    else
    {
      this.selectedCities = this.selectedCities.filter(x => x !== event.target.value);
    }
  }

Take a look at this Stackblitz illustrating this.

Comments

0

You can reference DOM element by using the # selector and viewchild. In your .ts you can get the element like this:

@ViewChild('yourSelector') anyName: Input

and then call any function that exists on the element. and in your .html you use the # selector:

<input #yourSelector type="checkbox"....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.