Angular 4动态地在按钮上添加单击事件

时间:2017-12-06 07:37:19

标签: angular typescript

这是循环显示的按钮代码。

for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "<tr>";            
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`; 
          break;    
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`; 
          break;    
        } else {
          myTable += "<td>" + this.newTmpArr[k][key2] + "</td>";                    
        }

    }
    myTable += "</tr>"; 
}

test(){
  alert("Working!");
}

以下是在动态数据呈现后页面的截图。

enter image description here

4 个答案:

答案 0 :(得分:3)

阅读详情:Dynamic Html Structure with - *ngIf, *ngFor & ngSwitch

你可以试试,下面的模板方式工作正常,没有太大的变化,下面只花了20分钟

App.Component.html ---模板文件

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th>Ammount</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
   <tr *ngFor="let ele of newTmpArr" >
     <td>{{ele[0]}}</td>
     <td>{{ele[1]}}</td>
     <td>{{ele[2]}}</td>
     <td>
        <div ngSwitch="{{ele[3]}}">
            <div *ngSwitchCase="'button'">
              <input type="button" (click)="DoWork(1)" value="click"/>
            </div>
            <div *ngSwitchCase="'link'">
                <a href="#" (click)="DoWork(1)" >click</a>
            </div>
        </div> 
     </td>
   </tr>
  </tbody> 
</table>

App.Component.ts - typescript

export class AppComponent implements OnInit {
ngOnInit(): void {}
title = 'app';
DoWork()
  {
    //here you can do work , 
    //this get called when you press "click" button in table 
    alert(this.title);
  }
}

没有模板动态方式

我花了5个小时才能达到这个代码但是满足以下工作正常,您需要在DomSanitizer的帮助下通过安全性,因为您希望从模板文件中输入输入元素。

//typings.d.ts
interface Window { my: any; }
上面的

扩展了你的窗口对象

app.Component.html

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th>Ammount</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody id="tid" [innerHTML]="bodytext"></tbody> 
</table>

typescript文件 - app.Component.ts

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import {Component, NgZone, OnInit, OnDestroy} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {
   title = 'app';
  _myTable : string;
  bodytext ;
  newTmpArr = [
          ["567", "2017-04-17T14:22:48", "45000", "button"],
          ["567", "2017-04-17T14:22:48", "45000", "button"],
          ["567", "2017-04-17T14:22:48", "45000", "link"],
          ["567", "2017-04-17T14:22:48", "45000", "button"]
        ];
   constructor(private http: Http,private _sanitizer: 
                 DomSanitizer,private ngZone: NgZone) {
   }

  ngOnInit(): void {
    //below code add dynamci table to your html
    for( let k=0; k<this.newTmpArr.length; k++ ){
            this._myTable += "<tr>";            
            for( let key2 in this.newTmpArr[k] ){
                if(this.newTmpArr[k][key2] == 'button' ){
                //below is table click button calls angular function, 
                //here 1 is passed as arugment you can pass 
                //any other value you want
                //or if you dont want to pass than just do
                // onclick="my.namespace.publicFunc();" 
                // and remove parameter from typscript function also 
                this._myTable += `<td><input  type="button" 
                   onclick="my.namespace.publicFunc(1);" 
                   value="Click me"  /></td>`; 
                break;    
                }
                if(this.newTmpArr[k][key2] == 'link' ){
                this._myTable += `<td><a href="#"
                        onclick="my.namespace.publicFunc(1); 
                             return false;">Click</a>
                         </td>`; 
                break;    
                } else {
                this._myTable += "<td>" + 
                   this.newTmpArr[k][key2] + "</td>";                    
                }
            }
            this._myTable += "</tr>"; 
        }
         this.bodytext = 
        this._sanitizer.bypassSecurityTrustHtml(this._myTable);
        //code to add dynamic html ends here 

         //below script helps to expose anglar function to javascript 
         window.my = window.my || {};
         window.my.namespace = window.my.namespace || {};
        //below line bind typescript function to window object publicFunc
         window.my.namespace.publicFunc = 
          this.OnTableButtonClick.bind(this);
        //code to expose typscipt function ends here 
  }

  //this function get called when Table click button ge clicked 
  public OnTableButtonClick(input:string):void{ 
    this.ngZone.run(() => this.DoWork(input)); 
  }

  DoWork(input:string)
  {
    //here you can do work , 
    //this get called when you press "click" button in table 
    alert(this.title + input);
    //this will display app1 in output
  }
}

答案 1 :(得分:1)

我会以有棱角的方式继续发布我觉得应该这样做的方式。在代码中编写HTML几乎总是意味着你做错了什么。这是模板逻辑,应该在模板中完成,如下所示:

<tr *ngFor="let row of newTmpArr">
  <td *ngFor="let cell of row">
    <ng-container [ngSwitch]="cell">
      <button *ngSwitchCase="'button'" (click)="test()">Click</button>
      <a *ngSwitchCase="'link'" href="#" (click)="test()">Click</a>
      <ng-container *ngSwitchDefault>{{ cell }}</ng-container>
    </ng-container>
  </td>
</tr>

这是实现目标的有条理的方式,所有这些都在模板中完成,使用嵌套的ng for循环然后ngSwitch是此用例的适当指令,因为您有2个选项和默认值。现在你不需要对抗框架或者使用像绑定函数这样的任何黑客攻击窗口。 Angular将使用此方法适当地绑定函数。您还拥有显卡驱动模型的独特优势,因此您只需更新模型,显示屏就会做出相应的反应,因此您无需担心显示屏和模型不同步。

例如,如果您要删除第5行,则需要在更新模型后手动重绘表格,如果添加新行,或者编辑第3行的单元格2,则需要手动重绘。使用模板,angular管理所有以透明和可靠的方式。

答案 2 :(得分:0)

如上所述,您可以在component.html文件的表格行中使用* ngFor。 然后在按钮标记中处理click事件,就像通常那样。

<td> <button (click)="clickEvent()"> Click </button> </td>

然后在component.ts文件中定义on click事件

clickEvent(){console.log("click event triggered")}

答案 3 :(得分:-1)

这是我的代码工作。它也可能对你们有帮助。

<tr *ngFor="let item of newTmpArr">
       <td *ngFor="let i of item">
          <span *ngIf="i.value; then dynamicVal; else elseblock"></span>
          <ng-template #dynamicVal>
          <span *ngIf="i.type == 'button'">
          <button (click)="clickMe(item)">Click</button>
          </span>
          <span *ngIf="i.type == 'link'">
             <a [href]="i.link">{{i.value}}</a>
          </span>
          </ng-template> 
          <ng-template #elseblock>{{i}}</ng-template>
       </td>
</tr>