Angular 6:如何构建一个简单的多个复选框以供用户选中/取消选中?

编程入门 行业动态 更新时间:2024-10-25 00:35:44
本文介绍了Angular 6:如何构建一个简单的多个复选框以供用户选中/取消选中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在阅读了几个关于这个主题的主题后写了这篇文章,但没有一个给我我需要的东西.这篇文章 似乎有解决方案,但我没有从 json 中读取选中的值.

我只需要:

从对象数组中读取国家动态构建代表每个国家/地区的复选框列表

用户应该选中和取消选中每个复选框

奖金:

获取已检查输入的值并将其发送到组件外

我知道这样做可能真的很愚蠢,但直到现在我所做的只是有一个不可选中的复选框列表,仅此而已.

代码如下:模板:

<div *ngFor="let country of countries"><输入类型=复选框"名称=国家"value="{{country.id}}"[(ngModel)]="国家"/><label>{{country.name}}</label>

和 TS:

国家= [{id: 1, name: 'Italia'},{id: 2, name: '巴西'},{id: 3, name: '佛罗里达'},{id: 4, name: 'Spagna'},{id: 5, name: 'Santo Domingo'},]

我尝试使用反应式表单,但这给我带来了比模板驱动更多的问题(当然是因为我的实现不好).请帮帮我,我不知道该往哪里撞了

解决方案

这是一个工作示例,您可以在其中观察到每个国家/地区添加了一个额外的选中"值,并使用 <绑定到每个复选框的值代码>[(ngModel)].

Stackblitz 实例

模板:

测试复选框</p><div *ngFor="let country of countries; let i = index;"><input type="checkbox" name="country{{country.id}}" [(ngModel)]="countries[i].checked"><label for="country{{country.id}}">{{country.name}}</label>

<button type="button" (click)="sendCheckedCountries()" *ngIf="countries">单击以发送所选国家/地区(请参阅您的 javascript 控制台)</button><p *ngIf="!countries">正在加载国家,请稍等...</p><p *ngIf="countries">调试信息:countries"数组的实时值:</p><pre>{{ 国家 |json }}</pre>

组件:

//...导出类 AppComponent 实现 OnInit {公共国家:国家[];构造函数(私人国家服务:国家服务){}公共 ngOnInit(): 无效 {//加载国家,模拟一些延迟setTimeout(() => {this.countries = this.countryService.getCountries();}, 1000);}//此函数执行将所选国家/地区发送出去的工作公共 sendCheckedCountries(): 无效 {const selectedCountries = this.countries.filter( (country) => country.checked );//您可以使用 EventEmitter 并在此处发出选定的值,或者将它们发送到具有某些服务的另一个 APIconsole.log (selectedCountries);}}

为了使用一些合适的 TypeScript,我创建了一个接口 Country :

接口国家{身份证号码;名称:字符串;检查?:布尔值;}

<小时>

我希望你现在明白了.

注意:一开始勾选的值不是自动存在"的,不过没关系.

当不存在时,它与undefined相同,并且在复选框和读取哪个国家被选中的函数中都将被视为false.

对于发送值"部分:

该按钮会将选定的值输出到浏览器的控制台,并带有一些类似于@Eliseo 的回答所建议的过滤器(我只是使用了完整的国家/地区对象而不是 id)

对于真正的用例"情况,您可以使用 Angular 的 EventEmitters 并让您的组件将值发送"给父组件,或者调用一些服务函数来向另一个 API 发出您的值的 POST 请求.

I am writing this post after having read several threads concerning this topic but no one of them gives me what I need. This post seems to have the solution but I do not have to read the checked values from the json.

All I need is to:

read countries from an array of objects build dinamically a list of checkbox representing each country

user should check and uncheck each checkbox

bonus:

get the value of the checked input and send it outside the component

I know It might be really dumb to do but all I have accomplished untile now is to have a list of uncheckable checkboxes and nothing more.

Here is the code: Template:

<div class="form-group">
    <div *ngFor="let country of countries">
        <input type="checkbox"
                  name="countries"
                  value="{{country.id}}"
                  [(ngModel)]="country"/>

        <label>{{country.name}}</label>
    </div>
</div>

And TS:

countries = [
    {id: 1, name: 'Italia'},
    {id: 2, name: 'Brasile'},
    {id: 3, name: 'Florida'},
    {id: 4, name: 'Spagna'},
    {id: 5, name: 'Santo Domingo'},
]

I tried to use the reactive forms but that gave me more issues then template driven (surely because of bad implementation of mine). Please, help me, I do not know where to bump my head anymore

解决方案

Here is a working example, where you can observe that an additional 'checked' value is added to each country, and bound to the value of each checkbox with [(ngModel)].

Stackblitz live example

template:

<p>
Test checkboxes
</p>

<div *ngFor="let country of countries; let i = index;">
  <input type="checkbox" name="country{{country.id}}" [(ngModel)]="countries[i].checked">
  <label for="country{{country.id}}">{{country.name}}</label>
</div>

<button type="button" (click)="sendCheckedCountries()" *ngIf="countries">Click to send the selected countries (see your javascript console)</button>

<p *ngIf="!countries">loading countries, please wait a second...</p>
<p *ngIf="countries">Debug info : live value of the 'countries' array:</p>

<pre>{{ countries | json }}</pre>

component :

//...
export class AppComponent implements OnInit  {
  public countries: Country[];

  constructor(private countryService: CountryService) {}

  public ngOnInit(): void {
    // loading of countries, simulate some delay
    setTimeout(() => {
       this.countries = this.countryService.getCountries();
    }, 1000);
  }

  // this function does the job of sending the selected countried out the component
  public sendCheckedCountries(): void {
    const selectedCountries = this.countries.filter( (country) => country.checked );
    // you could use an EventEmitter and emit the selected values here, or send them to another API with some service

    console.log (selectedCountries);
  }
}

To use some proper TypeScript, I made an interface Country :

interface Country {
    id: number;
    name: string;
    checked?: boolean;
}


I hope you get the idea now.

Note : the checked value is not "automatically there" at the beginning, but it doesn't matter.

When not there, it is the same as undefined, and this will be treated as false both in the checkbox and in the function that reads which country is checked.

For the "sending value" part :

The button will output the selected value to the browser's console, with some filter similar to what @Eliseo's answer suggests (I just used full country objects instead of ids)

For "real usecase" situation, you could use Angular's EventEmitters and have your component "emit" the value to a parent component, or call some service function that will make a POST request of your values to another API.

这篇关于Angular 6:如何构建一个简单的多个复选框以供用户选中/取消选中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 17:27:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   以供   复选框   构建一个   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!