1

DateRangeComponent我尝试使用和装饰器在按钮单击另一个( ViewerComponent)组件时发出数组。EventEmitterOutput

有一种getData()方法可以从服务DateRangeComponentEventEmitter发出数组。

@Output() dataEmitter = new EventEmitter<any[]>();

  constructor(private dataService: DataService) { }

  getData() {
    let fromDate = this.dateName[0];
    let toDate = this.dateName[1];

    this.dataService.findNameByDate(fromDate, toDate)
      .map(names => {
          this.names = names;
          this.dataEmitter.emit(this.names);
          //console.log(JSON.stringify(this.names));
        }
      )
  }

Input组件应该使用装饰器接收发出的数组:

@Input() names: any;

并且在 HTML 中有一个属性绑定:

<app-table *ngIf="selectedDate" [names]="names"></app-table>

但是接收有问题。怎么了?

堆栈闪电战

4

2 回答 2

4

您的发射器工作正常。问题出在接收器组件上。

您正在@Input()@Output(). 您不需要有Input()变量来接收发出的事件,而是需要注册Output事件。

Output在您的接收组件中注册事件为(dataEmitter)="names = $event"

<app-date-range (dataEmitter)="names = $event"></app-date-range>

而不是将名称声明为@Input() names: any;

只需将其声明为

names : Array<{}>;

分叉的堆栈闪电战

于 2018-06-28T14:56:23.407 回答
1

几件事。

你的 appComponent 必须是这样的:

//app.html

    <!--we use (dataEmiter) to get the changes, and [names] to send the properties -->
    <app-date-range (dataEmitter)="emit($event)"></app-date-range>
    <app-viewer [names]="names"></app-viewer>

//And the component like
export class AppComponent  {
 names:any[]=[];  //<--declare a variable
 emit(data:any[])
 {
   this.names=data;
 }
}

在您的查看器组件中,不放 *ngIf if app-table 标记,我选择放入 div 并使用 names.length

<div class="container">
  <div class="row" *ngIf="names.length">
    <app-table [names]="names"></app-table>
  </div>
</div>

如果要模拟获取,请更改服务功能 findByDate 之类的

findNameByDate(fromDate: String, toDate: String) {
    return Observable.of(this.data);
  }

当然,日期范围函数必须是

getData() {
    let fromDate = this.dateName[0];
    let toDate = this.dateName[1];

    this.dataService.findNameByDate(fromDate, toDate)
      .subscribe(names => {  //<---subscribe
          this.names = names;
          this.dataEmitter.emit(this.names);
          console.log(this.names);
        }
      )
  }
于 2018-06-28T15:12:46.360 回答