简体   繁体   English

如何以角度提交复选框值

[英]how to submit checkbox value in angular

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,对于 getCities(),我正在从 api 中获取数据,我刚刚在 li 标签中显示了这些数据,我在 deliama 如何提交复选框值,

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>

When using template driven forms, add NgModel to the element attributes.使用模板驱动的表单时,将NgModel添加到元素属性中。

You should also add a unique name to each li element to be able to differentiate between values:您还应该为每个li元素添加一个唯一的名称,以便能够区分值:

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

Stackblitz demo Stackblitz 演示

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方法如下所示:

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.看看这个Stackblitz 说明了这一点。

You can reference DOM element by using the # selector and viewchild.您可以使用 # 选择器和 viewchild 来引用 DOM 元素。 In your .ts you can get the element like this:在你的 .ts 你可以得到这样的元素:

@ViewChild('yourSelector') anyName: Input

and then call any function that exists on the element.然后调用元素上存在的任何函数。 and in your .html you use the # selector:并在您的 .html 中使用 # 选择器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM