formsarray 中的 formarray.controls 在角度 5 中意味着什么?

2024-02-25

我是 Angular 5 的新手,所以基本上仍在掌握这些概念。使用 Angular 关于反应式表单的文档作为示例(https://angular.io/guide/reactive-forms https://angular.io/guide/reactive-forms),给出以下代码:

<div formArrayName="secretLairs" class="well well-lg">
<div *ngFor="let address of secretLairs.controls; let i=index" 
 [formGroupName]="i" >
    <!-- The repeated address template -->
  </div>
  </div>

Secretlairs.controls 是什么意思?它是什么?根据角度,这意味着:

重复项的来源是 FormArray.controls,而不是 FormArray 本身。每个控件都是一个地址 FormGroup,这正是前面(现在重复的)模板 HTML 所期望的。

Secretlairs.controls 是否包含任何数据?我可以用任意类型的数据替换这部分并用从 webapi 获取的数据实例化的对象本身吗? 例如,代替

*ngFor="let address of secretLairs.controls

i use

*ngFor="let address of addresses

其中地址的类型为any,数据从数据库获取。


首先,有三种类型的表格 -FormControl, FormGroup, and FormArray- 全部继承自AbstractControl.

当您使用反应式表单进行验证并包括formGroupName, formControlName, or formArrayName在组件的模板中,您实际上是在声明式定义表单控件树和根之间的映射FormGroup model.

例如,给定以下模板:

<div [formGroup]="formGroup">
    <div formGroupName="personalInfo">
         First Name: <input type="text" formControlName="firstName"><br />
         Last Name: <input type="text" formControlName="lastName"><br />
    </div>
    <div formArrayName="cities">
        Top cities: <input *ngFor="let city of cities; index as i" type="text" [formControlName]="i">
    </div>
</div>

您正在声明性地设置一个用于收集信息的表单映射,这最终将生成特定格式的 JSON 对象。例如,给定上述表单模型,formGroup.value会返回:

{
   "personalInfo": {
        "firstName: 'John',
        "lastName: 'Smith'
    },
    "cities": [
        "New York",
        "Winnipeg",
        "Toronto"
    ]
 }

在模板中声明表单组的结构后,您需要强制创建相应的formGroup, formControl, and formArray在你的组件类中。当您设置每个表单时,您有机会设置其他参数:

  1. Initial Form Value
  2. Array of synchronous validators
  3. Array of asynchronous validators

这适用于任何抽象控件。

这就是给定上述模板的相应 formGroup 模型的样子:

export class AppComponent {
  firstName: string,
  lastName: string;
  cities: string[];
  @Input() formGroup: FormGroup;
  constructor(private fb: FormBuilder) {
    // setup initial values
    this.cities = ['New York', 'Winnipeg', 'Toronto'];
    this.firstName = 'John';
    this.lastName  = 'Smith';

    // create a formGroup that corresponds to the template
    this.formGroup = fb.group({
      firstName: [this.firstName, Validators.required],
      lastName: [this.lastName, Validators.required],
      cities: fb.array(this.cities.map(t=> fb.control(t, Validators.required)))
    })
  }
}

要绑定到任何表单的验证标志,您可以使用 rootformGroup以及用于查找特定组、控件或数组的路径字符串(支持点)。

例如:

<div *ngIf="formGroup.get('firstName').errors.required">First Name is Required</div>

希望这能够清楚地说明这一点。

[Edit]

更好的是,鉴于反应式表单主要是在模板中以声明方式设置模型,并在组件类中强制映射相同的模型,您应该考虑定义一个 JSON 模型并使用它。

例如,假设我们有一个自定义模型MyModel其中有一个firstName财产,lastName财产,以及cities财产。组件类如下所示:

 export class AppComponent {
  @Input() model: MyModel;
  @Output() modelChange: EventEmitter<MyModel>;

  @Input() formGroup: FormGroup;
  constructor(private fb: FormBuilder) {
    this.model = new EventEmitter<MyModel>();
    // create a formGroup that corresponds to the template
    this.formGroup = fb.group({
      firstName: [this.model.firstName, Validators.required],
      lastName: [this.model.lastName, Validators.required],
      cities: fb.array(this.model.cities.map(t=> fb.control(t, Validators.required)))
    });
  }

  onSubmit() {
     if (this.formGroup.valid) {
        this.model = this.formGroup.value;
        this.modelChange.next(this.model);
     }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

formsarray 中的 formarray.controls 在角度 5 中意味着什么? 的相关文章

  • Angular 6 Asp.Net(非 Core)Web Api CORS 请求失败

    我正在构建一个 Net Web Api 它将由 Angular 6 客户端使用 但出于某种原因 我无法使其在我的开发环境中工作 我从一个非常简单的 Web Api 开始 它只返回一个字符串 用于前端和后端测试目的之间的通信 GET api
  • Angular 2 - 突出显示更新的表格单元格

    如何在表中刷新改变其值的单元格 tr td product productName td td product price td tr 在组件中我有产品的输入 Input products Array
  • 角度订阅响应

    好吧 我对 Angular 还很陌生 所以我遇到了这个小问题 所以我遵循 Angular 指南 https angular io guide http https angular io guide http 所以我的问题是我的 http r
  • 如何在 RxJS 订阅方法中等待

    在 RxJS 主题的订阅回调内部 我想要await on an async功能 下面是打字稿转译器抱怨的代码示例 错误 131 21 TS2304 找不到名称 await async ngOnInit this subscriber dat
  • MatAutocomplete 值 X 显示

    我的自动完成显示具有以下定义的对象的值 export class Person id number name string cityName string 这是自动完成模板
  • 修剪日期格式 PrimeNG 日历 - 删除时间戳、角度反应形式

    我将以下内容推入我的反应形式 obj 中2016 01 01T00 00 00 000Z但我想要以下2016 01 01 有谁知道有一个内置函数可以实现上述目的 我已经搜索过文档here https www primefaces org p
  • 为什么 Angular 2 项目如此大 [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我们正在用 ng2 重写 ng1 项目 我们的 ng1 项目构建后大约有 8mb 我们对 ng2 的重写已经完成了大约四分之一 并且我
  • 元素不适应 Firefox 上的

    使用 ES6 ish D3js 模块运行 Angular 6 应用程序会导致 Firefox 出现问题 Chromium Chrome Safari 和 IE Edge 工作正常 伪代码看起来类似于 生产代码可以在下面找到
  • Windows 10 中的 npm 安装错误( npm install -g angular-cli )

    node v v4 5 0 npm v 5 0 1 有人在 Windows 10 中安装 angular cli 时遇到过这种问题吗 请尝试以下操作 step 0 运行这个命令 npm uninstall g angular cli npm
  • 415 不支持的媒体类型; Angular2 到 API

    我是 Angular 2 的新手 我面临着一个无法找到解决方案的问题 当我尝试从 Angular 2 发布到 API 时 我得到 415 不支持的媒体类型 角度2代码 onSubmit value any console log value
  • 角度 4 单击按钮功能未触发

    我正在尝试检查文本输入是否为空或不在角度 4 中 我没有为此使用表单 这只是一个输入字段 当我在下面的按钮中执行 addLocaton 函数时 需要进行检查 我的输入字段
  • Angular 2:使用正则表达式进行数字验证

    我正在尝试验证 IE 11 中的数字字段
  • 角度代理配置不起作用

    我不明白我错在哪里 附 已经尝试通过这个答案修复但仍然不起作用 Angular CLI 代理到后端不起作用 https stackoverflow com questions 39809008 angular cli proxy to ba
  • 全局未在 ../node_modules/socket.io-parser/is-buffer.js 中定义

    预先感谢您帮助我 我正在尝试在我的一个角度组件中连接套接字 但在浏览器的控制台中它会抛出一个错误 指出 Global 未在 Object node modules socket io parser is buffer js 中定义 这是我的
  • 创建 AoT 兼容的服务工厂

    我正在尝试为缓存服务创建一个服务工厂 主要要求是每次可以使用不同的字符串实例化单个服务 最终的结果会有多个cache每个服务都由唯一定义databaseName 每个缓存可以有一个或多个stores也由唯一定义storeName 其他服务将
  • 使用服务中的可观察量测试错误情况

    假设我有一个订阅服务功能的组件 export class Component ngOnInit this service doStuff subscribe data IData gt doThings data error Error g
  • 如何调试超时等待异步 Angular 任务?无法在角度页面上找到元素

    编辑 请注意 在 ernst zwingli 的帮助下 我找到了问题的根源 因此 如果您遇到相同的错误 他指出的修复之一可能会帮助您 我的问题是量角器本身的一个已知问题 如果您认为这可能是您 我已经扩展了我的步骤 以在我最初的问题之后查明问
  • FakeAsync/tick (Async/whenStable) 与 detectorChanges()

    您能帮我区分这两件事吗 根据我的理解 如果你只使用 observable 你可以使用 detectorChanges 因此 您可以直接更改组件属性或监视服务调用并返回可观察的值 然后调用 detectorChanges 更改将在 html
  • Angular 2 获取当前路线

    所以我需要以某种方式检查我是否在主页上执行某些操作 而在其他页面上则不执行此操作 该组件也在所有页面上导入 如果我在主页上 如何检测该组件 Thanks 尝试这个 import Router from angular router expo
  • 如何在 Angular 项目中使用 Bootstrap?

    我开始我的第一次Angular应用程序和我的基本设置已完成 我怎样才能添加引导程序我的申请 如果您可以提供一个示例 那么这将是一个很大的帮助 如果您使用Angular CLI要生成新项目 还有另一种方法可以使 bootstrap 可访问角度

随机推荐