简体   繁体   中英

Emit values from directive to component in Angular

I want to emit values from a Directive to a component that have template with applied directive on it. My directive uses elementRef and first what I wanna do is to change some style on a native element, then emit the inner text from the element to an array in the component. How can I do that?

Directive:

    import { Directive, ElementRef, EventEmitter, HostListener, Output } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  @Output() onEmittedNumber:EventEmitter<any> = new EventEmitter();

  constructor(private el: ElementRef) {}

  @HostListener('click') onClick() {
    if(this.el.nativeElement.style.backgroundColor){
      this.el.nativeElement.style.backgroundColor = ''
    }else{
      this.el.nativeElement.style.backgroundColor = 'yellow'
      this.onEmittedNumber.emit(this.el.nativeElement.innerText)
    }
    this.onEmittedNumber.emit(this.el.nativeElement.innerText)
  }




}

Content component with the directive applied HTML file

<div class="container-basic">
  <button appHighlight *ngFor="number of numbers; let i = index"  type="text" class="btn-custom1" id="btn{{i}}">{{numbers[i]}}</button>
</div>

Ts file

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {

  numbers = Array.from(Array(51).keys()).slice(1)
  numbersChosen = [];
  constructor() { 
  }

  ngOnInit() {
  }

  onEmittedNumber(number){
    this.numbersChosen.push[number]
    console.log(this.numbersChosen)
  }

}

In the markup you should handle the output like this:

<div class="container-basic">
    <button
    appHighlight
    *ngFor="number of numbers; let i = index"
    type="text"
    class="btn-custom1"
    id="btn{{i}}"
    (onEmittedNumber)="onEmittedNumber($event)"
  >
    {{numbers[i]}}
  </button>
</div>

Note, to pass the event argument you should use special parameter $event . One more thing - looking at your onEmittedNumber function in ContentComponent I think you have misspelled the call to push . It should be like this:

  onEmittedNumber(number){
    this.numbersChosen.push(number);
    console.log(this.numbersChosen);
  }

Change [number] with (number)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM