【问题标题】:determine if checkbox is selected angular typescript确定复选框是否被选中
【发布时间】:2018-06-30 07:01:01
【问题描述】:

想要使用 if 语句确定是否已在最新版本的 Angular 中选择了复选框。

我的代码:

<mat-menu #wj="matMenu">
   <section><mat-checkbox (id)='1' (click)="$event.stopPropagation()">Cool Kids</mat-checkbox></section>
</mat-menu>

<div class="float-right">
 <mat-action-row>                           
  <button mat-button color="primary" (click) = "generateLink()" >Generate Link</button>
</mat-action-row>

AND IN component.ts:

generateLink() {
    <HTMLInputElement>document.getElementById('1')
    if(<HTMLInputElement>document.getElementById('1')){
        console.log('y');
    }      
}

这个想法是,一旦按下提交按钮,generateLink() 方法将评估以查看所有由 ID 选中的复选框。如果有更好的方法可以做到这一点,请分享。本质上,有 15 个复选框,我需要在最后按下提交按钮时将它们的所有值收集到一个数组中。

【问题讨论】:

  • 您使用的是 AngularJS 还是 Angular 2+?我删除了 AngularJS,因为它看起来好像您使用的是 Angular 2+,而 angularjs 是该框架的错误标签。
  • angular 2,我很抱歉
  • 您错过了角度的全部要点:您不应该从 DOM 获取值。真实的单点是模型,视图绑定到模型。阅读表单指南,并将您的输入绑定到您的模型。然后你可以从模型中知道复选框是否被选中。 angular.io/guide/reactive-forms

标签: angular typescript


【解决方案1】:

首先,你应该知道 mat-checkbox 会为 MatCheckbox 对象生成一个内部 id。

其次,我同意您应该通过 Forms 管理您的元素状态。

但是,如果您仍想跟踪某些复选框是否被选中,您可以跟踪它。

链接:stackblitz.com

简单地说,我正在使用服务将每个选定的复选框作为 MatCheckbox 对象发出。

然后,当单击 Button 时,我遍历 MatCheckbox 数组,每次迭代都会评估 checked 对象并将其 id 打印到控制台,仅用于演示目的。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    我的建议是改用响应式表单。这样,您可以更好地控制表单。

    // In your typescript
      myForm: FormGroup;
      mycheckboxControl: FormControl;
    
      constructor(private _fb: FormBuilder) {
        this.mycheckboxControl = new FormControl();
        this.mycheckboxControl
          .valueChanges.subscribe((res) => console.log(res));
    
        this.myForm = this._fb.group({
         checkobx: this.mycheckboxControl
        });
      }
    // In your HTML
    <form [formGroup]="myForm">
    <input type="checkbox" [formControl]="mycheckboxControl">
    

    You can play more with form here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-18
      • 2011-06-12
      • 2012-06-08
      • 2021-07-16
      • 1970-01-01
      • 2015-12-28
      相关资源
      最近更新 更多