• angular2动态增加一行组件和删除组件示例


    1. 在根模块下导入

    import { ReactiveFormsModule } from '@angular/forms';
     
    2.ts 文件
    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { FormGroup, FormBuilder ,FormArray } from '@angular/forms';
    @Component({
      selector: 'app-news',
      templateUrl: './news.component.html',
      styleUrls: ['./news.component.css']
    })
    export class NewsComponent  {

      constructor(private router: Router, private formBuilder: FormBuilder) { }

      public fg:FormGroup =this.formBuilder.group(
        { 
          // 创建数组对象
          arrayList:this.formBuilder.array([])
        }
      );

      /**
       * 获取数组对象
       */
      get arrayList()
      {
        return this.fg.get('arrayList') as FormArray;
      }

      /**
       * 创建一行组件
       */
     createRow(){
       return this.formBuilder.group({
          firstName:[''],
          age:[''],
          profession:[''],
        });
     }
     /**
      * 增加一行事件
      */
     addBtn(){
      this.arrayList.push(this.createRow());
     }
     /**
      * 删除一行事件
      */
     delBtn(i:number){
       this.arrayList.removeAt(i);
     }
     
    }
     
    3.HTML 
     

    <form [formGroup]="fg">
    <table class="table table-bordered">
        <tr><td>姓名</td><td>年龄</td><td>职业</td><td></td></tr>
        
        <ng-container formArrayName='arrayList'>
        <ng-container *ngFor="let row of arrayList.controls;let i =index">
            <tr>
            <ng-container [formGroup]="row">
            <td>
                <input type="text" class='form-control'  formControlName="firstName">
            </td>
            <td>
                <input  type="text"class='form-control'  formControlName="age">
            </td>
            <td>
                <input  type="text" class='form-control'  formControlName="profession">
            </td>
             
             <td>
                <button class='form-control' (click)="delBtn(i)">删除</button>
            </td>
       
        </ng-container>
    </tr> 
        </ng-container>
        </ng-container>

    </table>
    </form>
    <button (click)="addBtn()">添加</button>
     
    4.引入bootstrap
  • 相关阅读:
    MySQL数据库操作(7)联表查询、事务
    MySQL数据库操作(6)查询
    MySQL数据库操作(5)表关系
    Python零基础入门第1章.环境搭建
    Python零基础入门教程目录
    6.函数与代码复用
    元组
    列表
    复数(complex)
    浮点数类型(float)
  • 原文地址:https://www.cnblogs.com/kukai/p/12173982.html
Copyright © 2020-2023  润新知