search
HomeWeb Front-endJS TutorialA brief analysis of how to use FormArray and modal boxes in Angular

How to use FormArray and modal box together? The following article will introduce to you how to use Angular's FormArray and modal box together. I hope it will be helpful to you!

A brief analysis of how to use FormArray and modal boxes in Angular

Business scenario

Use FormArray to create dynamic forms. Every time a form is created, a new input is added to the page to display the title of the form. Click Edit and jump to click the fill-in content of the form. [Related tutorial recommendations: "angular tutorial"]

    // 封装获取modelList
    get modelList() {
        return this.formGroup.get('modelList') as FormArray
    }
    constructor(private fb: FormBuilder) {}
    ngOnInit() {
        // 一开始初始化arr为空数组
        this.formGroup = this.fb.group({
            // 内部嵌套FormControl、FormArray、FormGroup
            modelList: this.fb.array([])
        })
    }
    // 模态框构造内部的表单
    function newModel() {
        return this.fb.group({
            modelName: [''],
            // 可以继续嵌套下去,根据业务需求
        })
    }
    // 省略模态框部分代码
    // 传递到模态框的FormArray
    selectedType: FormArray

Form list

A brief analysis of how to use FormArray and modal boxes in Angular

Form Details [Modal Box]

A brief analysis of how to use FormArray and modal boxes in Angular

<form [FormGroup]="formGroup">
    <div FormArrayName="modelList">
        <ng-container *nfFor="let item of modelList.controls;let i = index" [FormGroupName]="i">
            <nz-input-group
                [nzSuffix]="suffixIconSearch"
              >
                <input type="text" nz-input formControlName="modelName"/>
              </nz-input-group>
              <ng-template #suffixIconSearch>
                <span
                  nz-icon
                  nzType="edit"
                  class="hover"
                  (click)="showModal(i)"
                ></span>
              </ng-template>
        </ng-container>
    </div>
</form>
<nz-modal
  [(nzVisible)]="isVisible"
  nzTitle="Model"
  [nzFooter]="modalFooter"
  (nzOnCancel)="handleCancel()"
  (nzOnOk)="handleOk()"
>
  <ng-container *nzModalContent>
    <form nz-form [formGroup]="selectedType">
      <nz-form-item>
        <nz-form-label nzRequired>Model Test</nz-form-label>
        <nz-form-control>
          <input
            type="text"
            nz-input
            placeholder="请输入ModelName"
            formControlName="modelName"
          />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control>
          <product-config></product-config>
        </nz-form-control>
      </nz-form-item>
    </form>
  </ng-container>
  <ng-template #modalFooter>
    <button *ngIf="!isNewModel" nzDanger nz-button nzType="default" (click)="handleDelete()">删除</button>
    <button *ngIf="isNewModel" nz-button nzType="default" (click)="handleCancel()">取消</button>
    <button nz-button nzType="primary" (click)="handleOk()">保存</button>
  </ng-template>
</nz-modal>

Because this kind of modal box is special, it separates the relationship between the FormGroup of the form and needs to be passed when clicking. The parameters are sent to the modal box to display part of the value. If you simply pass the parameters and use this.modelList.at(index) to obtain the entity and assign the value to the modal box for modification, you will find the modification after clicking Save in the modal box. The value is not updated in the form, and modifications to the input value on the form are found to affect the content of the modal box.

But the form added by the modal box can be responded to the page.

Original error code idea

  • After clicking edit, pass the clicked FormArray element to a temporary variable this.selectedType = <formgroup>this.modelList.at(index);</formgroup>, and pass the value to the modal box form.

  • Click to save the modal box and replace the original FormArray value again

this.modelList.removeAt(this.modelIndex)
this.modelList.insert(this.modelIndex, this.selectedType)

  • ##Click to add , create a new FormGroup object

  • Save and add push to the FormArray of the original page

  • newModelType(): FormGroup {
        return this.fb.group({
          modelName: [&#39;&#39;, Validators.required],
          configList: this.fb.array([]),
        });
      }
    // ...省略
    // 模态框显示
    show() {
        this.isVisible = true
        this.selectedType = this.newModelType();
    }
    // 保存
    save() {
        this.isVisible = false
        // 原页面FormArray
        this.modelList.push(this.selectedType);
    }
Finally found that this writing method can only be used in one direction Change, the modified value of the input outside the page will affect the modal box, but the value of the modal box is changed and saved, but the outside is not updated. Checking the internal parameters of the FormArray of the page through the console method found that there were actually changes, but Angular did not detect it. At this time, it is judged that the reason why there is no response is generally that the angular detection mechanism is not triggered. After carefully checking the document, I found that there is a very important line

angular document at the bottom that says

A brief analysis of how to use FormArray and modal boxes in Angular

When I first read it, I felt that I followed this principle, because when editing, I chose to manipulate the original FormArray to delete and insert elements, which followed this rule, but in fact, in the modal box Assignment already violates this principle. When assigning value, I took the element instance of FormArray and assigned it to the temporary variable of the modal box, then changed the value of the instance, and deleted the insertion again. Essentially, I was operating the same instance. So angular did not detect the change [although the value changed]

A brief analysis of how to use FormArray and modal boxes in Angular

So what is the correct approach? ?

Don't be lazy when assigning values. You still have to re-create a new object and then get the assigned value of the original object. [Equivalent to deep copy]

      this.selectedType = this.newModelType();
      const old = this.modelList.at(index);
      this.selectedType.setValue({
        &#39;modelName&#39;: old.get(&#39;modelName&#39;).value
    })

You can update normally at this time.

Summary

In fact, in the end, it was essentially a return to the document. There are also many pitfalls in troubleshooting errors, and there are basically no angular articles in China, so we have to rely on external forums to find problems.

For more programming-related knowledge, please visit:

Programming Teaching! !

The above is the detailed content of A brief analysis of how to use FormArray and modal boxes in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Angular学习之聊聊独立组件(Standalone Component)Angular学习之聊聊独立组件(Standalone Component)Dec 19, 2022 pm 07:24 PM

本篇文章带大家继续angular的学习,简单了解一下Angular中的独立组件(Standalone Component),希望对大家有所帮助!

angular学习之详解状态管理器NgRxangular学习之详解状态管理器NgRxMay 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

项目过大怎么办?如何合理拆分Angular项目?项目过大怎么办?如何合理拆分Angular项目?Jul 26, 2022 pm 07:18 PM

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

聊聊自定义angular-datetime-picker格式的方法聊聊自定义angular-datetime-picker格式的方法Sep 08, 2022 pm 08:29 PM

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

浅析Angular中的独立组件,看看怎么使用浅析Angular中的独立组件,看看怎么使用Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

手把手带你了解Angular中的依赖注入手把手带你了解Angular中的依赖注入Dec 02, 2022 pm 09:14 PM

本篇文章带大家了解一下依赖注入,介绍一下依赖注入解决的问题和它原生的写法是什么,并聊聊Angular的依赖注入框架,希望对大家有所帮助!

Angular的:host、:host-context、::ng-deep选择器Angular的:host、:host-context、::ng-deep选择器May 31, 2022 am 11:08 AM

本篇文章带大家深入了解一下angular中的几个特殊选择器:host、:host-context、::ng-deep,希望对大家有所帮助!

深入了解angular中的@Component装饰器深入了解angular中的@Component装饰器May 27, 2022 pm 08:13 PM

Component是Directive的子类,它是一个装饰器,用于把某个类标记为Angular组件。下面本篇文章就来带大家深入了解angular中的@Component装饰器,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft