【问题标题】:Angular 5, HTML, boolean on checkbox is checkedAngular 5, HTML, boolean on checkbox被选中
【发布时间】:2018-08-08 09:59:51
【问题描述】:

Angular 5,打字稿 2.7.1

返回布尔值时,我似乎无法检查复选框,我试过了,item.check 返回 true 或 false。

<tr class="even" *ngFor="let item of rows">
<input value="{{item.check}}" type="checkbox" checked="item.check">

检查后始终选中复选框输入内部输入。并且checked="false" 时不会取消选中。

有没有更好的方法来代替 Angular 功能?比如 ngModel 或 ngIf???

解决方案

<input type="checkbox" [checked]="item.check == 'true'">

【问题讨论】:

  • 假设 item 是一个在您的 ts 中包含检查布尔值的对象 - 在您的复选框上使用 ngModel。 [(ngModel)]="item.check"

标签: html angular typescript


【解决方案1】:

当您拥有对象的副本时,[checked] 属性可能不起作用,在这种情况下,您可以通过这种方式使用 (change)

<input type="checkbox" [checked]="item.selected" (change)="item.selected = !item.selected">

【讨论】:

    【解决方案2】:

    使用可观察对象处理复选框

    您甚至可以选择使用 behaviourSubject 来利用 observable 的力量,这样您就可以从 isChecked$ observable 开始一定的反应链。

    在您的 component.ts 中:

    public isChecked$ = new BehaviorSubject(false);
    toggleChecked() {
      this.isChecked$.next(!this.isChecked$.value)
    }
    

    在您的模板中

    <input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">
    

    【讨论】:

      【解决方案3】:

      你可以用这个:

      <input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">
      

      这里,记录是当前行的模型,状态是布尔值。

      【讨论】:

      • 如何从 ts 组件中的 $event 中提取布尔值?
      • @svichkar 提取你必须使用 event.target.checked 值。如果为 true ,则选中复选框,否则取消选中。
      【解决方案4】:

      希望这将帮助某人开发具有自定义样式的自定义复选框组件。此解决方案也可以与表单一起使用。

      HTML

      <label class="lbl">
      
        <input #inputEl type="checkbox" [name]="label" [(ngModel)]="isChecked" (change)="onChange(inputEl.checked)"
         *ngIf="isChecked" checked>
        <input #inputEl type="checkbox" [name]="label" [(ngModel)]="isChecked" (change)="onChange(inputEl.checked)"
         *ngIf="!isChecked" >
        <span class="chk-box {{isChecked ? 'chk':''}}"></span>
        <span class="lbl-txt" *ngIf="label" >{{label}}</span>
      </label>
      

      checkbox.component.ts

          import { Component, Input, EventEmitter, Output, forwardRef, HostListener } from '@angular/core';
      import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
      
      const noop = () => {
      };
      
      export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => CheckboxComponent),
        multi: true
      };
      
      /** Custom check box  */
      @Component({
        selector: 'app-checkbox',
        templateUrl: './checkbox.component.html',
        styleUrls: ['./checkbox.component.scss'],
        providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
      })
      export class CheckboxComponent implements ControlValueAccessor {
      
      
        @Input() label: string;
        @Input() isChecked = false;
        @Input() disabled = false;
        @Output() getChange = new EventEmitter();
        @Input() className: string;
      
        // get accessor
        get value(): any {
          return this.isChecked;
        }
      
        // set accessor including call the onchange callback
        set value(value: any) {
          this.isChecked = value;
        }
      
        private onTouchedCallback: () => void = noop;
        private onChangeCallback: (_: any) => void = noop;
      
      
        writeValue(value: any): void {
          if (value !== this.isChecked) {
            this.isChecked = value;
          }
        }
      
        onChange(isChecked) {
          this.value = isChecked;
          this.getChange.emit(this.isChecked);
          this.onChangeCallback(this.value);
        }
      
        // From ControlValueAccessor interface
        registerOnChange(fn: any) {
          this.onChangeCallback = fn;
        }
      
        // From ControlValueAccessor interface
        registerOnTouched(fn: any) {
          this.onTouchedCallback = fn;
        }
      
        setDisabledState?(isDisabled: boolean): void {
      
        }
      
      }
      

      checkbox.component.scss

         @import "../../../assets/scss/_variables";
      /* CHECKBOX */
      
      .lbl {
          font-size: 12px;
          color: #282828;
          display: -webkit-box;
          display: -ms-flexbox;
          display: flex;
          -webkit-box-align: center;
          -ms-flex-align: center;
          align-items: center;
          cursor: pointer;
          &.checked {
              font-weight: 600;
          }
          &.focus {
            .chk-box{
              border: 1px solid #a8a8a8;
              &.chk{
                border: none;
              }
            }
          }
          input {
              display: none;
          }
      
          /* checkbox icon */
          .chk-box {
              display: block;
              min-width: 15px;
              min-height: 15px;
              background: url('/assets/i/checkbox-not-selected.svg');
              background-size: 15px 15px;
              margin-right: 10px;
          }
          input:checked+.chk-box {
              background: url('/assets/i/checkbox-selected.svg');
              background-size: 15px 15px;
          }
          .lbl-txt {
              margin-top: 0px;
          } 
      
      }
      

      用法

      外部表格

      <app-checkbox [label]="'Example'" [isChecked]="true"></app-checkbox>
      

      内部表格

      <app-checkbox [label]="'Type 0'" formControlName="Type1"></app-checkbox>
      

      【讨论】:

        【解决方案5】:

        这是我的答案,

        在 row.model.ts 中

        export interface Row {
           otherProperty : type;
           checked : bool;
           otherProperty : type;
           ...
        }
        

        在.html中

        <tr class="even" *ngFor="let item of rows">
           <input [checked]="item.checked" type="checkbox">
        </tr>
        

        在 .ts 中

        行:行[] = [];

        更新component.ts中的行

        【讨论】:

          【解决方案6】:

          尝试:

          [checked]="item.checked"
          

          签出:How to Deal with Different Form Controls in Angular

          【讨论】:

          • 谢谢你,我试过了,但我需要添加 然后就可以了,谢谢
          • 那是因为你的 item.check 是 String 而不是 Boolean item.check = true; //boolean item.check = 'true'; //字符串
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-08-21
          • 2022-11-23
          • 2018-10-06
          • 2017-05-18
          • 2013-12-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多