Angular 5, HTML, boolean on checkbox 被选中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49030977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:08:59  来源:igfitidea点击:

Angular 5, HTML, boolean on checkbox is checked

htmlangulartypescript

提问by Mr. Toast

Angular 5, Typescript 2.7.1

角 5,打字稿 2.7.1

I can't seem to get the checkbox to be checked when returning a boolean, I've tried, item.checkreturns either true or false.

我似乎无法在返回布尔值时选中要检查的复选框,我已经尝试过,item.check返回 true 或 false。

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

The checkbox is always checked when checked is written inside input. And it does not get unchecked when checked="false".

选中后始终检查复选框。当checked="false".

Is there a better way to do it with Angular features instead? like ngModel or ngIf???

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

Solution

解决方案

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

回答by ProfitWarning

回答by Abdus Salam Azad

You can use this:

你可以使用这个:

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

Here, record is the model for current row and status is boolean value.

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

回答by Janith Widarshana

Hope this will help somebody to develop custom checkbox component with custom styles. This solution can use with forms too.

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

HTML

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

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

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;
    } 

}

Usage

用法

Outside forms

外部表格

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

Inside forms

内部表格

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

回答by Colo Ghidini

When you have a copy of an object the [checked]attribute might not work, in that case, you can use (change)in this way:

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

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

回答by Dhanika

Here is my answer,

这是我的答案,

In row.model.ts

在 row.model.ts

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

In .html

在 .html 中

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

In .ts

在 .ts

rows : Row[] = [];

行:行[] = [];

update the rows in component.ts

更新 component.ts 中的行