即使它是@Input也无法绑定宽度

时间:2017-08-09 18:02:54

标签: angular checkbox initialization controls

自定义复选框已将[已选中]作为@Input属性。无论它们是未定义的,“真实的”还是“假的”,都会始终检查屏幕上的复选框。 HTML - 顺便说一句,它们处于无序列表中,它们不是一种形式。

<checkbox id="UpperCaseLetter" #chkb [checked]="true" [disabled]="false">Upper Case Letter</checkbox>
<checkbox id="LowerCaseLetter" #chkb >Lower Case Letter</checkbox>
<checkbox id="NumericDigits" #chkb [checked]="false">Numeric Digits</checkbox>
<checkbox id="NonAlphanumericChars" #chkb [checked]="true">Non-Alphanumeric Chars</checkbox>

复选框HTML(简单:-)):

<input type="checkbox"
   checked="{{checked}}"
   [disabled]="isDisabled"
   (change)="onChange($event)" />
<span><ng-content></ng-content></span>

Checkbox.component.ts - 你可以看到我已经尝试将事情移到AfterInit,但没有任何工作。

import {AfterViewInit, Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {ElementState, PageMgrService} from '../page-mgr.service';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Component({
  selector: 'checkbox',
  templateUrl: './checkbox.component.html',
  styleUrls: ['./checkbox.component.scss']
})
export class CheckboxComponent implements OnInit, AfterViewInit {
  @Input() id: string;
  @Input() checked: boolean;
  @Input('disabled') isDisabled: boolean;
  @Output('onChange') onChangeEvent = new EventEmitter;
  FSubj: BehaviorSubject<ElementState>;
  value: boolean;
  InstanceId = 'PasswordConfigAdmin';
  constructor(private pagMgr: PageMgrService) {
    this.InstanceId = pagMgr.GetUniquePageId();
    this.FSubj = pagMgr.GetSubject();
  }

  ngOnInit() {
    this.value = (this.checked === null || this.checked === undefined || this.checked === false ? false : true);
  }

  ngAfterViewInit() {
    this.checked = (this.checked === null || this.checked === undefined || this.checked === false ? false : true);
    this.controlChanged(this.id, this.checked);
  }

  getValue(): boolean {
    return this.value;
  }

  setValue(val: boolean) {
   this.value = val;
   this.checked = val;
  }

  setDisabled(val: boolean) {
    this.isDisabled = val;
  }

  onChange($event) {
    this.value = $event.target.checked;
    this.controlChanged(this.id, this.value);
  }

  controlChanged(ctrl: string, arg: any) {
    const elt = new ElementState();
    elt.controlId = ctrl;
    elt.value = arg;
    elt.instance = this.InstanceId;
    this.FSubj.next(elt);
  }

}

似乎很直接,但??提前感谢您的建议。

1 个答案:

答案 0 :(得分:1)

来自MDN:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-checked

  

选中当type属性的值为radio或checkbox时,   此布尔属性的存在表示控件是   默认情况下选中,否则会被忽略。

我认为这样就可以将HTML用于检查:

<input type="checkbox"
   checked
   [disabled]="isDisabled"
   (change)="onChange($event)" />

或者这是未经检查的:

<input type="checkbox"
   [disabled]="isDisabled"
   (change)="onChange($event)" />

您可以使用以下方式实现目标:

<input *ngIf='checked' type="checkbox"
   checked
   [disabled]="isDisabled"
   (change)="onChange($event)" />
<input *ngIf="!checked" type="checkbox"
   [disabled]="isDisabled"
   (change)="onChange($event)" />