How to create a custom directive - Angular 6

1

I created a custom directive in angular , and I want to share a value between my directive and my typescript file, this is an example of my 2 files:

<!-- Mi html --> 
<div>
  <input type="radio" name="colors" (click)="color='lightgreen'">Green
  <input type="radio" name="colors" (click)="color='yellow'">Yellow
  <input type="radio" name="colors" (click)="color='cyan'">Cyan
</div>
<p [appHighlight]="color">Highlight me!</p>
<p *ngIf="color">True</p>

<p [appHighlight]="color" defaultColor="violet">
  Highlight me too!
</p>

 <!-- mi typescript --> 
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  color: boolean;
}
<!-- mi directiva custom -->
/* tslint:disable:member-ordering */
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) {}
  @Input() color: boolean;
  @Input() defaultColor: boolean;

  @Input('appHighlight') highlightColor: string;

  @HostListener('mouseenter')
  onMouseEnter() {
    console.log(this.color);
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

By changing the Boolean value to true or false , my% ngIf evaluates it and shows me the <p *ngIf="color">True</p> properly.

But when changing the value in my directive *ngIf does not evaluate it, how can I communicate the value of my directive with my .ts ?

    
asked by Isack Rubio 01.08.2018 в 18:27
source

1 answer

1

So that your directive can not only receive but also send values you have to use @Output .

If you look at your code you have @Input for things that are going to enter the directive, @Output serves to remove.

In your case you would have to define your output variable as a EventEmitter , and when you want to issue a value you use the emit method.

  @Output() colorOut = new EventEmitter();

  @HostListener('mouseleave')
  onMouseLeave() {
    this.highlight(null);
    this.colorOut.emit(null);
  }

And in your component, in the HTML template you must use the exit event, the emitted value will be in $event :

<p [appHighlight]="color" (colorOut)="color = $event">Highlight me!</p>
    
answered by 01.08.2018 / 21:13
source