當我需要在角2+ CheckBox組件,它似乎直覺做你正在嘗試做同樣的事情。爲什麼從一個通用控件開始,當你可以從一個複選框開始時,對吧?在花費太多時間後,我決定放棄並使用ControlValueAccessor
。
正如你可以this plnkr看到,CheckBox組件可以這樣寫:
import { Component, /*Input,*/ Renderer, ElementRef, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'my-checkbox',
template: `
<div class="checkbox-container">
<input type="checkbox" id="{{ controlID }}"
[checked]="checked" (change)="onChange($event)" />
<label for="{{ controlID }}"></label>
</div>
`,
styles: [`
.checkbox-container {
background-color: #ddd;
width: 20px;
height: 20px;
position: relative;
}
`, `
.checkbox-container input[type="checkbox"] {
visibility: hidden;
}
`, `
.checkbox-container label {
width: 18px;
height: 18px;
position: absolute;
top: 1px;
left: 1px;
background-color: white;
}
`,`
.checkbox-container label:before {
content: '';
width: 16px;
height: 8px;
border: 4px solid #000;
position: absolute;
border-top: none;
border-right: none;
transform: rotate(-50deg);
top: 1px;
left: 1px;
opacity: 0;
}
`, `
.checkbox-container input[type="checkbox"]:checked + label:before {
opacity: 1;
}
`],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxComponent),
multi: true
}
]
})
export class CheckboxComponent implements ControlValueAccessor {
static idCounter: Number = 0;
controlID: String;
//@Input() checked: Boolean;
checked: Boolean;
constructor(private renderer: Renderer, private elementRef: ElementRef) {
this.controlID = "myCheckbox" + CheckboxComponent.idCounter++;
}
propagateChange = (_: any) => { };
onTouchedCallback:() => {};
writeValue(value: any) {
if ((value !== undefined) && (value !== null)) {
this.checked = value;
}
}
registerOnChange(fn: any) {
this.propagateChange = fn;
}
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
};
onChange(event) {
this.checked = event.target.checked;
this.propagateChange(event.target.checked);
}
}
,並可以這樣使用:
<form #form="ngForm" (ngSubmit)="submit(form.value)">
<div>
<h2>Checkbox Demo Using {{ framework }}</h2>
</div>
<div>
<my-checkbox name="b1" [(ngModel)]="b1"></my-checkbox>
<my-checkbox name="b2" [(ngModel)]="b2"></my-checkbox>
<my-checkbox name="b3" [(ngModel)]="b3"></my-checkbox>
</div>
</form>
<pre>{{ form.value | json }}</pre>
注:
controlID
必須是唯一的,這可以使用靜態計數器來完成。
- 我決定不要讓
checked
成爲 Input()變量,因爲您可以使用外部變量ngModel
完成相同的操作。
- 爲簡單起見,僅刪除了其他功能並且省略了其他功能。