Angular Checkbox教程与最新实例

819 阅读1分钟

本教程解释了关于复选框的教程,并附有以下例子

  • 双向绑定示例
  • 动态复选框列表
  • 在Angular中获取复选框的值
  • 如何发现复选框是否被选中

前提条件

首先,使用Angular cli - ng命令创建一个angular application1on。

一旦应用程序被创建,依赖性被安装,你可以开始导入FormsModule

在应用模块中导入FormsModuleReactiveFormsModule ,这些模块是Angular应用中输入表单绑定工作所必需的。

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";

import { AppComponent } from "./app.component";
import { HelloComponent } from "./hello.component";

@NgModule({
  imports: [BrowserModule, FormsModule, ReactiveFormsModule],
  declarations: [
    AppComponent,
    HelloComponent,
    
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Angular复选框双向绑定示例

Angular中的双向绑定提供了从html到typecript组件的数据传递,反之亦然。

这可以通过简单的ngModel语法实现 - [()] 。

<input [(ngModel)]="isAccepted" type="checkbox" name="isAccepted" />

这等同于属性[] 和事件绑定() 语法。

<input [ngModel]="isAccepted"(isAcceptedChange)="isAccepted==$event"type="checkbox" 
name="isAccepted" />

在typescript组件中

@Input() ngModel;
@Output() isAcceptedChange = new EventEmitter();

完整的html代码示例:


<h3>
  Checkbox Basic Two way binding Example
</h3>
<div>
  <input [(ngModel)]="isAccepted" type="checkbox" name="isAccepted" />Is
  Accepted

  <h1>{{ isAccepted }}</h1>
  >
</div>

在typescript组件中:

  • 声明带有类型和可选默认值的属性变量。
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-checkbox-component-basic",
  templateUrl: "./checkbox-component-basic.component.html",
  styleUrls: ["./checkbox-component-basic.component.css"]
})
export class CheckboxComponentBasicComponent implements OnInit {
  constructor() {}
  isAccepted = true;

  ngOnInit() {}
}

这就是双向绑定在Angular输入表单的复选框中是如何工作的

Angular动态复选框例子

这个例子解释了Typescript有一个json对象,它有一个值列表,并创建一个动态复选框。

在typescript中,创建一个接口来保存值的列表。

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

在typescript组件中,Roles对象被初始化为数据。然而这可以通过调用Http GET服务从数据库中获取。这里将不涉及这个问题。

你可以让Role对象的检查值为true或false,以使复选框在默认情况下被选中。还写了getter- selectedCheckboxList,检索用户选择的checkbox json对象。

import { Component, OnInit } from "@angular/core";
import { Role } from "../role";

@Component({
  selector: "app-dynamic-checkbox-list",
  templateUrl: "./dynamic-checkbox-list.component.html",
  styleUrls: ["./dynamic-checkbox-list.component.css"]
})
export class DynamicCheckboxListComponent implements OnInit {
  public roles: Role[];

  constructor() {}

  ngOnInit() {
    this.roles = [
      {
        id: 1,
        name: "users",
        checked: true
      },
      {
        id: 2,
        name: "admin",
        checked: false
      },
      {
        id: 3,
        name: "support",
        checked: true
      },
      {
        id: 4,
        name: "manager",
        checked: false
      }
    ];
  }
   get selectedCheckboxList() {
    return this.roles.filter(item => item.checked);
  }
}

在Html模板中:

  • 使用*ngFor 指令来迭代角色对象。
  • 添加了输入复选框,并绑定了迭代的checked属性,这可以实现双向绑定。
  • 添加了带有对象名称值的标签
  • 显示带有选中的复选框值列表的json对象。
<h1>
  Dynamic Checkbox List Example
</h1>
<ul>
  <li *ngFor="let role of roles">
    <input type="checkbox" [(ngModel)]="role.checked" />
    <label>{{role.name}}</label>
  </li>
</ul>

And the select Object is

<pre>{{this.selectedCheckboxList | json}}</pre>

这样,我们就可以从json对象中绑定动态复选框并获得所选复选框列表。

如何使用变更事件处理程序获得复选框的值?

有时,我们需要跟踪复选框的状态变化。

像JavaScript事件处理程序一样,Angular提供了改变事件。

在Html模板中,在输入元素中添加了(改变)事件处理程序 - termsChange。它接受$event参数。

 <input (change)="termsChange($event)" value="terms" type="checkbox" /> Terms

在Typescript组件中。

提供带有任何类型的参数的函数。

选定的复选框值可以通过target.checked属性获得。

  termsChange(selected: any): void {
 console.log(
      selected.target.name,
      selected.target.value,
      selected.target.checked
    );
      }

在一个函数中,检索复选框的名称和值以及是否选中。这样,你就可以在Angular中获得选中的复选框的值,并且在复选框被选中时调用函数。

你如何知道复选框是否在checked ?在一个变化回调处理程序中,写下以下几行代码

if(selected.target.checked){
    //checked
    // own logic
}
else{
    // not checked
    // logic 
}

结论

本教程涵盖了Angular复选框教程与ngmodal 绑定、动态列表、检索值的例子