【问题标题】:Table row on click function is not working in Angular7点击功能上的表格行在Angular7中不起作用
【发布时间】:2019-09-09 11:43:58
【问题描述】:

每当我单击 HTML 表格中的一行时,我都会尝试调用一个函数,但它不工作并且没有给出任何错误。

我已经尝试了几件事,在线代码显示我尝试的方式应该可以工作。

我的代码如下:

HTML:

<h2>Userstories</h2>

<button (click)="onNewStory()">New Story</button>

<table>
  <tr *ngFor="let story of userstories" ng-click="onUpdate(story)" [class.selected]="story === selectedStory">
      <td>{{story.id}}</td>
      <td>{{story.name}}</td>
      <td><button ng-click="onUpdate(story)">Click me!</button></td>
  </tr>
</table>

<app-userstory-detail [story]="selectedStory"></app-userstory-detail>

我的 .ts 看起来像这样:

  selectedStory: UserStory;
  onNewStory() {
    var newStory = {id:this.userstories[this.userstories.length-1].id+1, name:"", description:"Deze is nieuw", status:"open", owner:USERS[1]};
    this.userstories.push(newStory);
    this.selectedStory = newStory;
  }

  onUpdate(userstory: UserStory): void {
    this.selectedStory = userstory;
    console.log(this.selectedStory);
  }

当前,当我尝试调用 onUpdate 方法时,我的控制台没有打印日志。预期的结果是在日志中看到一些输出,但我不知道为什么它没有触发 onUpdate 方法。

【问题讨论】:

  • (click)替换ng-click

标签: html angular angular7


【解决方案1】:

在 Angular 7 中,您可以使用 (click),它类似于 Angular JS 的 ng-click

试试:

<h2>Userstories</h2>

<button (click)="onNewStory()">New Story</button>

<table>
  <tr *ngFor="let story of userstories" (click)="onUpdate(story)" [class.selected]="story === selectedStory">
      <td>{{story.id}}</td>
      <td>{{story.name}}</td>
      <td><button (click)="onUpdate(story)">Click me!</button></td>
  </tr>
</table>

<app-userstory-detail [story]="selectedStory"></app-userstory-detail>

StackBlitz Demo

【讨论】:

    【解决方案2】:

    ng-click 实际上是针对 AngularJS (1.x)

    你想使用(click),它是 Angular 的。

    文档:https://angular.io/guide/ajs-quick-reference#ng-click

    【讨论】:

      【解决方案3】:

      事件被触发两次。在&lt;tr&gt;&lt;button&gt; 中。 试试这个:

      <h2>Userstories</h2>
      
      <button (click)="onNewStory()">New Story</button>
      
      <table>
        <tr *ngFor="let story of userstories" [class.selected]="story === selectedStory">
            <td>{{story.id}}</td>
            <td>{{story.name}}</td>
            <td><button (click)="onUpdate(story)">Click me!</button></td>
        </tr>
      </table>
      
      <app-userstory-detail [story]="selectedStory"></app-userstory-detail>
      

      【讨论】:

        猜你喜欢
        • 2020-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-29
        • 2017-11-14
        • 2017-01-12
        相关资源
        最近更新 更多