将变量从指令传递给组件

时间:2018-05-15 14:41:15

标签: angular

使用Angular,我创建了一个带有sort指令的表,该指令根据单击的标题对表进行排序。我希望在排序生效时使用*ngIf来显示符号,但是当我们更改时,我需要将变量this.keythis.togglesort传递给组件。

我该怎么做?

我的指示是:<​​/ p>

import { Directive, OnInit, Input, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appSort]'
})
export class SortDirective implements OnInit {
  @Input() data: any[];
  @Input('sortKey') key: any;
  private toggleSort: boolean = false;

  str1;
  str2

  constructor(private el: ElementRef, private renderer: Renderer2) {
  }

  ngOnInit() {
    this.renderer.listen(this.el.nativeElement, 'click', (event) => {
      let parentNode = this.el.nativeElement.parentNode;
      let children = parentNode.children;

      if (this.data && this.key) {
        let sortedData: any = this.sortArray();
      }
      this.toggleSort = !this.toggleSort;
    })
  }

  sortArray(): Array<any> {
    console.log( this.key, this.toggleSort) //CORRECTLY LOGS ITEMS
    .....
  }
}

修改:我已创建了Stackblitz for this issue.

1 个答案:

答案 0 :(得分:0)

我能够通过使用Angular的EventEmitter和Output装饰器来解决这个问题。

以下代码已添加到指令中:

import { ...,Output, EventEmitter } from '@angular/core';

...

export class SortDirective implements OnInit {
  ...

  @Output() onSortEvent = new EventEmitter();

  ...

  sortArray(): Array<any> {
  ...
  this.onSortEvent.emit({key: this.key, toggle: this.togglesort})
  // REVIEW: EventEmitter can only take one argument; passing object is workaround
  ...
  }
}

每个标题的HTML来自:

<th appSort [sortKey]="'Id'" [data]="scorecardItems">Item ID</th>
<th appSort [sortKey]="'AccountNum'" [data]="scorecardItems">Account</th>
...

为:

<th appSort [sortKey]="'Id'" [data]="scorecardItems" (onSortEvent)="sortEventOnParent($event)">Item ID</th>
<th appSort [sortKey]="'AccountNum'" [data]="scorecardItems" (onSortEvent)="sortEventOnParent($event)">Account</th>
...

我现在可以使用以下命令记录组件中的变量:

sortEventOnParent(event){
  console.log(event);
}

现在可以在转换为全局变量后使用*ngIf

Here is a working example