Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 @Input undefined when trying to bind to a string constant

Tags:

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

Plunker

like image 966
Angel Angel Avatar asked Mar 14 '16 23:03

Angel Angel


1 Answers

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

  • Using host property
@Directive({
    host:{
        '(mouseenter)' : ' mouseEnter()',
        '[style.background-color]' : 'myColor'
    }
})

mouseEnter(){
    this.myColor = 'blue';
}
  • Using @HostBinding (this case will set the color immediatly)
@HostBinding('style.background-color') get color {
    return this.myColor;
}

mouseEnter(){
    this.myColor = 'blue';
}
  • Using 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);
}
like image 175
Eric Martinez Avatar answered Oct 12 '22 01:10

Eric Martinez