Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional attribute binding

Tags:

angular

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?

like image 422
Steven Liekens Avatar asked Nov 27 '17 15:11

Steven Liekens


People also ask

What does an attribute binding DO?

Attribute binding basically allows you to bind attributes of elements from the component to the view template.

How to bind attribute in Angular 2?

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.

How to bind class property in Angular?

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.

How to do style binding in Angular?

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.


2 Answers

Hope this helps you

<input type="checkbox" [attr.name]="name?name :null">
like image 76
Paka Avatar answered Oct 04 '22 19:10

Paka


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.

like image 44
GHB Avatar answered Oct 04 '22 18:10

GHB