将标签连接到复选框组件

时间:2018-07-02 21:30:27

标签: angular typescript angular-forms

我创建了一个自定义复选框组件,如下所示:

checkbox.component.ts

import {Component, Input, OnInit, forwardRef} from "@angular/core"
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"

@Component({
    selector: "checkbox",
    template: `
        <input type="checkbox" [checked]="checked" (change)="checkedChanged($event)" [id]="id">
        <label [for]="id"><span>{{checked ? "&#10003;" : "&nbsp;"}}</span></label>
    `,
    styles: [`
        input {
            opacity: 0;
            position: fixed;
        }
        label {
            line-height: 16px;
            height: 16px;
            width: 16px;
            border-radius: 5px;
            font-size: 16px;
            color: #000000;
            background-color: #ffffff;
            margin-bottom: 0;

            -webkit-touch-callout: none;
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }
    `],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => CheckboxComponent),
            multi: true
        }
    ]
})
export class CheckboxComponent implements OnInit, ControlValueAccessor {
    static idCounter = 1

    @Input() id: string

    checked: boolean
    propagateChange = (_: any) => {}
    onTouchedCallback = () => {}

    ngOnInit () {
        // If an ID wasn't provided, generate a unique one
        if (!this.id) {
            this.id = "checkboxcomponent" + CheckboxComponent.idCounter++
        }
    }

    checkedChanged (event) {
        this.checked = event.target.checked
        this.propagateChange(event.target.checked)
    }

    // ControlValueAccessor requirements
    writeValue (value: any) {
        this.checked = value
    }
    registerOnChange (func: any) {
        this.propagateChange = func
    }
    registerOnTouched (func: any) {
        this.onTouchedCallback = func
    }
}

html示例

<div class="col-4 text-right">
    <label for="foo">Foo:</label>
</div>
<div class="col-8">
    <checkbox [(ngModel)]="bar" id="foo"></checkbox>
</div>

复选框本身可以正常工作,但标签却不能。我想传递ID作为输入,以便可以将其连接到外部标签(应用程序不同部分的标签位置不同,因此无法将其包含在组件中),并检查页面显示它使用的是正确的ID,但单击标签不会切换复选框。我认为这是组件的范围界定问题,但是我不确定如何处理。有没有一种方法可以使它工作,而不必每次使用时都添加额外的(click)功能或其他功能?

1 个答案:

答案 0 :(得分:4)

如果您更改

@Input id: string;

@Input checkboxId: string;

并在<checkbox [(ngModel)]="bar" checkboxId="foo"></checkbox>中使用它就可以了。

https://stackblitz.com/edit/angular-qxjb4q