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?
Attribute binding basically allows you to bind attributes of elements from the component to the view template.
Attribute binding syntax resembles property binding, but instead of an element property between brackets, you precede the name of the attribute with the prefix attr , followed by a dot. Then, you set the attribute value with an expression that resolves to a string.
Class Binding in Angular In property binding, we only specify the element between brackets. But in the case of class binding, it starts with the prefix class, followed by a dot (.), and the name of the class. You then bind the class value with CSS class name like class. class-name.
To create a single style binding, use the prefix style followed by a dot and the name of the CSS style. Angular sets the property to the value of the bound expression, which is usually a string. Optionally, you can add a unit extension like em or % , which requires a number type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With