详细阅读: 使用-ngIf、*ngFor和ngSwitch实现动态Html结构
您可以尝试,下面的模板方式工作良好,几乎没有改变,以下只花了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()
{
alert(this.title);
}
}
没有模板动态方式
我花了5个小时才写出这段代码,但之后它可以正常工作,你需要使用 DomSanitizer
来绕过安全性检查,因为你想要在模板文件中放置输入元素。
//typings.d.ts
interface Window { my: any; }
上述代码扩展了您的window对象。
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 {
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' ){
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);
window.my = window.my || {};
window.my.namespace = window.my.namespace || {};
window.my.namespace.publicFunc =
this.OnTableButtonClick.bind(this);
}
public OnTableButtonClick(input:string):void{
this.ngZone.run(() => this.DoWork(input));
}
DoWork(input:string)
{
alert(this.title + input);
}
}