事件发射器:模板对发射的事件没有反应

时间:2019-05-24 12:09:29

标签: angular angular-material angular-event-emitter

我有一个子组件可以发出这样的事件

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

HTML是

  <mat-row *matRowDef="let row; columns: displayedColumns;" class="my-mat-cell" (click)="setAdditionalCodeValue.emit(row)">
      </mat-row>

然后,我的父HTML这样绑定到setAdditionalCodeValue

<ng-container matColumnDef="additionalCode">
  <th mat-header-cell *matHeaderCellDef mat-sort-header>Additional Code</th>
  <td mat-cell *matCellDef="let element" class="grandParent" >
    <mat-form-field class="type" let="i = index">
      <input matInput (keyup)="toggleLookup($event, element)" (setAdditionalCodeValue)="updateAdditionalCodeHandler(element)" [(ngModel)]="countryLookupInput" autocomplete="off" (keydown.ArrowDown)="onDown()">
    </mat-form-field>
    <div *ngIf="element.expanded" class="parent">
      <app-lookup-popup class="child" (closeLookup)="closeLookupHandler(element)" ></app-lookup-popup>
    </div>
  </td>
</ng-container>

父组件看起来像

  updateAdditionalCodeHandler(evt) {
console.log('Update Addition Code event received: ' + evt);
this.countryLookupInput = evt;

}

未点击updateAdditionalCodeHandler,因为没有任何内容写入控制台开始。

我的最终目标是更新'countryLookupInput' 属性,其值从子级的'row'参数发出。

奇怪的是,以同样的方式连接的'(closeLookup)="closeLookupHandler(element)"',请花点时间!

2 个答案:

答案 0 :(得分:1)

问题出在下面的元素中:

 <app-lookup-popup class="child" (closeLookup)="closeLookupHandler(element)" ></app-lookup-popup>

修改后的代码

<app-lookup-popup class="child" (closeLookup)="closeLookupHandler(element)" (setAdditionalCodeValue)="updateAdditionalCodeHandler(element)" ></app-lookup-popup>

和其他组件

<input matInput (keyup)="toggleLookup($event, element)"[(ngModel)]="countryLookupInput" autocomplete="off" (keydown.ArrowDown)="onDown()">

如果这是发出事件的组件

答案 1 :(得分:0)

我认为您的代码中有两个问题,首先是您在input而不是您的子组件上处理了事件

我的意思是这里->

  <input matInput (keyup)="toggleLookup($event, element)" (setAdditionalCodeValue)="updateAdditionalCodeHandler(element)"

代替这里->

  <app-lookup-popup class="child" (closeLookup)="closeLookupHandler(element)" ></app-lookup-popup>

第二个问题是您需要使用$event来访问发出的值

因此下面修改的代码应该可以工作

<ng-container matColumnDef="additionalCode">
  <th mat-header-cell *matHeaderCellDef mat-sort-header>Additional Code</th>
  <td mat-cell *matCellDef="let element" class="grandParent" >
    <mat-form-field class="type" let="i = index">
      <input matInput (keyup)="toggleLookup($event, element)"  [(ngModel)]="countryLookupInput" autocomplete="off" (keydown.ArrowDown)="onDown()">
    </mat-form-field>
    <div *ngIf="element.expanded" class="parent">
      <app-lookup-popup class="child" (closeLookup)="closeLookupHandler(element)" 
 (setAdditionalCodeValue)="updateAdditionalCodeHandler($event)" ></app-lookup-popup>
    </div>
  </td>
</ng-container>