【问题标题】:Angular 8: Add Div dynamicallyAngular 8:动态添加 Div
【发布时间】:2020-10-03 21:33:37
【问题描述】:

下面是我的 HTML 代码。

<div class="row" style="padding-bottom: 5%;">

          <div class="col-md-12" id="HolidayDiv">
            <div class="form-group row justify-content-md-center m-b-10">
              <label class="col-md-4 text-md-right col-form-label">
                <div>HOLIDAY NAME</div>
                <div><input type="text" name="firstname" placeholder="" class="form-control"></div>
              </label>

              <label class="col-md-4 text-md-right col-form-label">
                <div>HOLIDAY DATE</div>
                <div>
                  <div class="input-group date" data-provide="datepicker">
                    <input type="text" class="form-control">
                    <div class="input-group-addon">
                      <span class="far fa-calendar-alt"></span>
                    </div>
                    <i class="fas fa-lg fa-fw m-r-10 m-l-5 m-t-10 text-grey fa-indent"></i>
                  </div>
                </div>
              </label>
            </div>
          </div>
          <!-- end #content -->
          <!-- end col-10 -->
        </div>

下面是截图。
这里小红框添加按钮大红框是我需要在下面动态添加的。

下面是我的 typescript 文件。

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'CustomerProfileAdd',
  templateUrl: './CustomerProfileAdd.html',
  styleUrls: ['./CustomerProfileAdd.css']
})

export class CustomerProfileAdd {
  active = 1;  
}

因为我有几个例子,但只有 https://stackblitz.com/edit/angular-pujraw?file=src%2Fapp%2Fapp.component.csshttps://stackblitz.com/edit/dynamically-add-rows-gk4veg?file=app%2Fapp.component.html 但对于除法我找不到它。

【问题讨论】:

  • 你必须使用ngFor and and and array 来做到这一点。当您执行array.push 时,Angular 会在该列表中添加另一个元素

标签: html angular typescript angular8


【解决方案1】:

使用反应式形式。它具有适用于各种表单操作的强大功能。首先从here 了解反应式表单。使用 FormBuilder 构建动态数组并在单击按钮时调用此方法

addRowsToTable(): void {
    this.sampleTableForm = this.FormBuilder.group({ you can pass your row defintion : 
    yourRow[] });
    let index: number = 1;
    const row: FormGroup = this.fBuilder.group({
        reactiveFormField1: [null, Validators.required],
        reactiveFormField2: [null, Validators.required],
        .....
    });

    this.yourrow.push(row);
    index++;
}

【讨论】:

    【解决方案2】:

    如果您使用的是响应式表单,我认为此视频完全解释了解决该问题的方法:https://youtu.be/JeeUY6WaXiA?t=346

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 2021-02-05
      • 2013-06-13
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 2021-08-04
      相关资源
      最近更新 更多