Angular2 - Override Host Binding?

1,499 views
Skip to first unread message

Cagatay Civici

unread,
Jan 18, 2016, 1:43:57 PM1/18/16
to AngularJS
Hi,

When writing a custom attribute directive, if I create a property name that overlaps with the property-attribute name of the html element, does anyone know if I can override it with no side effects? For example;

import {Directive, ElementRef, OnInit, OnDestroy, HostBinding,Input,OnChanges,SimpleChange} from 'angular2/core';

@Directive({
    selector: '[pSpinner]'
})
export class SpinnerDirective implements OnInit, OnDestroy, OnChanges {

    @Input('disabled') disabled;

    constructor(private el: ElementRef) {}

}

Usage is like;

<input type="text" [disabled]="disabledValueAtComponent" />

So setting disabledValueAtComponent = true does not disable the input, so it seems like my disabled property at directive is overriding a regular attribute binding to an html element right?

Thank you,

Cagatay

michael corbridge

unread,
Jan 18, 2016, 2:11:36 PM1/18/16
to AngularJS
Are you using the @Input decorator correctly?

I use it in my components in this format:

@Input() person:string;

Eric Martinez

unread,
Jan 18, 2016, 2:20:39 PM1/18/16
to AngularJS
Yes, this is by design, see https://github.com/angular/angular/pull/3419

So since you have a directive in the element and binding to a property using brackets, that property it doesn't belong anymore to the element but to the directive. As specified in the message in the issue referenced above you have to use host property to reset the attribute you're trying to set in the element


@Directive({
    selector
: '[pSpinner]',
   
host : {
      '[attr.disabled]' : 'disabled'

   
}
})
export class SpinnerDirective implements OnInit, OnDestroy, OnChanges {
   
@Input('disabled') disabled;
}

See if it works with "[attr.disabled]", or just "[disabled]", I don't remember/know if it is an attribute or a property.

michael corbridge

unread,
Jan 18, 2016, 2:49:38 PM1/18/16
to AngularJS
Thanks Eric!

Cagatay Civici

unread,
Feb 2, 2016, 3:13:09 PM2/2/16
to AngularJS
Lately I've removed the () from the @Input but it is also valid to map a property name to a variable in your directive.

@Input("something") somethingElse;

Cagatay Civici

unread,
Feb 2, 2016, 3:13:34 PM2/2/16
to AngularJS
Awesome, good design choice! Thanks.
Reply all
Reply to author
Forward
0 new messages