javascript - Angular 6:如何使用 Angular 6 在单击按钮时动态添加和删除一行 2 个文本框
问题描述
我有一个角度项目,用户可以单击添加按钮以在每次单击时再生成 2 个文本框,并类似地在单击按钮时删除相应的行。应该允许创建最多 5 行和一个默认的空文本框行开始时。
输入的数据需要用于 2 路数据绑定,同时在编辑时会有所帮助。
我从这里得到的以下代码我用数字修改了一点,它具有所需的功能,但我在 Angular 6 中需要相同的功能。由于我在 jquery 中的想法较少并且是 Angular 的新手,请帮助我解决这个问题的插件条件在开始时默认有一排文本框。
var x=1;
var count=0;
//click Event for the add button
$('body').on('click','#add',function(){
if(count <= 5){
//add the two inputs + the reset button to a div with class 'line' then append
//this div to #div
$('#div').append("<div class='line'><input type='text' id='txta"+ x +"'><span class='wordtab'></span><input type='text' id='txtb"+ x +"'><button class='delete' value='Reset'>Reset</button></div>");
count++;
x++
}
else
alert("Maximum 5 Skills");
});
//click Event for the delete button
$('body').on('click','.delete',function(){
//when the user click on delete get the parent div with class 'line' of clickable
//button and remove it
$(this).closest('.line').remove();
count--;
});
.wordtab
{
min-width: 85px;
display: inline-block;
}
.line{
margin-bottom: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>
<button id='add' value="Add Row">Add Row</button>
提前致谢 :)
解决方案
请按照以下程序使用 angular 6/7 添加动态内容:
- 创建一个新的角度项目。
- 安装引导程序和烤面包机,因为我们将使用以下命令进一步使用它:
npm install bootstrap
npm install ngx-toastr --save
- 在 angular.json 文件中添加 bootstrap 和 toaster 的引用。
"Styles":[
"node_modules/bootstrap/dist/css/bootstrap.css",
"node_modules/ngx-toastr/toastr.css",
]
4.使用以下命令创建一个新组件
ng g c grid-view --routing
- 键入以下命令以生成该类的模型文件。
ng g class grid.model
6.打开根文件夹中的 app.module.ts 文件并在其中添加引用。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ToastrModule } from 'ngx-toastr';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GridViewComponent } from './grid-view/grid-view.component';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent,
GridViewComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule ,
BrowserAnimationsModule,
ToastrModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
7.打开 app.component.html 文件并在其中添加代码。
<div class="container">
<app-grid-view></app-grid-view>
</div>
8.打开 index.html 文件并添加 font-awesome 的引用。(如果你想使用 font awesome 图标)。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DynamicGrid</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
</head>
<body>
<app-root></app-root>
</body>
</html>
9.打开 grid.model.ts 文件并在其中添加类。
export class DynamicGrid{
title1:string;
title2:string;
title3:string;
}
10.打开 grid-view.component.html 文件,在其中添加 HTML 代码。
<div class="container" style="margin-top: 5%">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Action</th>
<th>Title 1</th>
<th>Title 2</th>
<th>Title 3</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let dynamic of dynamicArray; let i = index;">
<td (click)="deleteRow(i)">
<i class="fa fa-trash fa-2x"></i>
</td>
<td>
<input [(ngModel)]="dynamicArray[i].title1" class="form-control" type="text" />
</td>
<td>
<input [(ngModel)]="dynamicArray[i].title2" class="form-control" type="text" />
</td>
<td>
<input [(ngModel)]="dynamicArray[i].title3" class="form-control" type="text"/>
</td>
</tr>
<tr>
<td (click)="addRow(i)">
<i class="fa fa-plus fa-2x"></i>
</td>
</tr>
</tbody>
</table>
</div>
11.最后,为 grid-view.component.ts 文件编写以下代码。
import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { DynamicGrid } from '../grid.model';
@Component({
selector: 'app-grid-view',
templateUrl: './grid-view.component.html',
styleUrls: ['./grid-view.component.css']
})
export class GridViewComponent implements OnInit {
constructor(private toastr: ToastrService) { }
dynamicArray: Array<DynamicGrid> = [];
newDynamic: any = {};
ngOnInit(): void {
this.newDynamic = {title1: "", title2: "",title3:""};
this.dynamicArray.push(this.newDynamic);
}
addRow(index) {
this.newDynamic = {title1: "", title2: "",title3:""};
this.dynamicArray.push(this.newDynamic);
this.toastr.success('New row added successfully', 'New Row');
console.log(this.dynamicArray);
return true;
}
deleteRow(index) {
if(this.dynamicArray.length ==1) {
this.toastr.error("Can't delete the row when there is only one row", 'Warning');
return false;
} else {
this.dynamicArray.splice(index, 1);
this.toastr.warning('Row deleted successfully', 'Delete row');
return true;
}
}
}
您也可以点击链接:https ://www.c-sharpcorner.com/article/dynamically-add-and-remove-row-in-angular-7/
推荐阅读
- encryption - 通过 SFTP 传输时是否需要加密数据
- java - 如何使 docker 容器向同一网络中运行的另一个容器发送 HTTP 请求
- scala - Spark SQL with Scala:registerTempTable 的弃用警告
- r - 控制分类变量 R 的限制输出
- coq - 应用策略后如何让 coq 打印出新的目标和假设
- aws-lambda - 如何将 Cloud9 (python) 连接到 VPC 中的 Redshift?
- swift - 鼠标事件后自定义 Carbon 键事件处理程序失败
- android - java.net.UnknownHostException:主机是未解析的 SOCKS 代理
- javascript - 在常规inetrvals mvc中登录到Web应用程序后检测用户活动更新数据库
- c - C - fprintf 返回访问冲突写入位置 0x00246D1C