Optional attribute binding

Viewed 10088

I'm building a custom checkbox component that wraps a real input and makes it look stylish.

One requirement for my custom checkbox is being able to bind an optional name so that the checkbox can be submitted as part of a form.

@Component({
    selector: 'my-checkbox'
    template: `
    <input type="checkbox" [name]="name">
    `
    /*, ...etc */
})
export class MyCheckbox implements ControlValueAccessor {
    @Input() name: string;

    // ...etc
}

Usage:

<!-- named-->
<my-checkbox [(ngModel)]="vm" name="coolcool"></my-checkbox>

<!-- unnamed-->
<my-checkbox [(ngModel)]="vm"></my-checkbox>

The output of the named example looks just fine

<!-- named output -->
<my-checkbox>
    <input type="checkbox" name="coolcool">
</my-checkbox>

...but the output of the unnamed example also has a name attribute?!

<!-- unnamed output -->
<my-checkbox>
    <input type="checkbox" name="undefined">
</my-checkbox>

How do I make name="undefined" go away?

2 Answers

Hope this helps you

<input type="checkbox" [attr.name]="name?name :null">

you can simply change the template inside the MyCheckbox 's template to this:

<input *ngIf="!(!name)" type="checkbox" [name]="name">
<input *ngIf="!name" type="checkbox">

update:

checked this, works with input and name: try changing the binding from [name]="name" to [attr.name]="name" and see if it works.

Related