The relationship between custom directive and component in Angular2

I have a template with a text box, a span tag and a div tag.

'div' has a special directive selectedColor. I want to change the background color of the span and div tags when the input value changes.

So, I want my directive to respond to input changes and set the background color of the div tag.

I also want to change the background color "span" in the input value change event.

Plunker

boot.ts

import {Component,bind} from 'angular2/core';

import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';
import {selectedColorDirective} from 'src/directive';
import {Directive, ElementRef, Renderer, Input} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
      <input type="text" [(ngModel)]="color"  />
      <br>
      <span > I'm {{color}} color <span>
      <div [mySelectedColor]="color"> I'm {{color}} color </div>
    `,
    directives: [selectedColorDirective]
})

export class AppComponent{

  color:string;
  constructor(el:ElementRef,renderer:Renderer)
  {
    this.color="Yellow";
    renderer.setElementStyle(el, 'backgroundColor', this.color);
  }
 }

    bootstrap(AppComponent, []);

directive.ts

import {Directive, ElementRef, Renderer, Input} from 'angular2/core';

@Directive({

  selector:"[mySelectedColor]", 
    host: {
    // '(keyup)': 'changeColor()',
    '(blur)': 'changeColor()',
  }

  })

  export class selectedColorDirective{ 

    @Input('mySelectedColor') selectedColor: string;

    constructor(el: ElementRef, renderer: Renderer) {
        //el.nativeElement.style.backgroundColor = 'yellow'; 
       renderer.setElementStyle(el, 'backgroundColor', this.selectedColor);
    } 

    changeColor(color:string)
    {
       console.log('Changed Detection' + " " + selectedColor);
       //this.renderer.setElementStyle(this.el, 'backgroundColor', this.color);
     }
  }

Also, if you could talk more about the @Input decorator.

+4
source share
2 answers

@Input() someName: SomeType ,

<div [mySelectedColor]="color" 
    [someName]="someFieldInParent"> I'm {{color}} color </div>

- .

export class AppComponent{
  @ViewChild(selectedColorDirective) myDirective: selectedColorDirective;

  ngAfterViewInit() {
    myDirective.changeColor('red');
  }
}

class CSS .

, , http://plnkr.co/edit/nm8RgxMtqdEDyQWQGeUp?p=preview

, , . [(myDirective)]="someField".

host: {
  '(keyup)': 'changeColor()',
  '[style.color]': 'selectedColor', // <==
}

( AppComponent, ). ElementRef Renderer. ElementRef Renderer <span>, , .

+4

:

constructor(el: ElementRef) {
 el.nativeElement.style.backgroundColor = "yellow";
}
0

Source: https://habr.com/ru/post/1624749/


All Articles