Maybe this is normal behavior, making a test, this.myColor
It is undefined, but why? That mistake wrong in my code:
<h1 myDR [myColor]="red" > Test </h1>
import {Component, Directive, Input, ElementRef} from 'angular2/core';
@Directive({
selector: '[myDR]',
host:{
'(mouseenter)' : ' mouseEnter()'
}
})
export class MyDi {
@Input () myColor: string;
constructor(private el:ElementRef) {
}
mouseEnter(){
this.el.nativeElement.style.backgroundColor = this.myColor;
console.log(this.myColor);
}
}
@Component({
selector: 'my-app',
template: `<h1>Hello World Angular2</h1>
<h1 myDR [myColor]="red" > Test </h1>
`,
directives: [MyDi]
})
export class App {
constructor(){
}
}
You can move the mouse over "Test" and look in the Console
You have to enclose your input binding in simple quotes, like this
[myColor]="'red'"
This will bind the red
string to myColor
. If you remove the simple quotes it will look for a class property named red
which doesn't exist therefore it returns undefined
You can do it as I mentioned above, or you can create a class property named red
. In this case it will bind to the class property.
@Component({
template: `<h1 myDR [myColor]="red" > Test </h1>`
})
export class App {
red: string = 'red';
}
Edit
I forgot to mention that accessing the DOM through nativeElement
is discouraged. You should use Renderer, @HostBinding or the host
property in @Component
(the last two are equivalent). So you have three more options
host
property@Directive({
host:{
'(mouseenter)' : ' mouseEnter()',
'[style.background-color]' : 'myColor'
}
})
mouseEnter(){
this.myColor = 'blue';
}
@HostBinding
(this case will set the color immediatly)@HostBinding('style.background-color') get color {
return this.myColor;
}
mouseEnter(){
this.myColor = 'blue';
}
Renderer
(use this instead of nativeElement.style = 'value'
)constructor(public renderer: Renderer, public element: ElementRef) {}
mouseEnter(){
this.renderer.setElementStyle(this.element.nativeElement, 'background-color', this.myColor);
}
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