Angular表单

文章目录一、[ngModelOptions]="{standalone: true}" 是什么意思?为什么在我们的项目中使用ngModel的时候需要用到?二、ng表单和表单验证 (https://angular.cn/guide/forms-overview)2.1 目前Angular中提供的内置验证器有2.2 创建自定义验证器2.3 如何将错误信息展示在模板中三、创建自定义表单组件需要用到Con...
摘要由CSDN通过智能技术生成


Shark用得过于熟练,却不大了解的ng表单,在使用shark的过程中产生了以下一些疑问。

一、[ngModelOptions]="{standalone: true}" 是什么意思?为什么在我们的项目中使用ngModel的时候需要用到?

<shark-select  [(ngModel)]="channelId" [data]="channelList"></shark-select>

在表单中直接这么写会报错

ChannelListComponent.html:13 ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form
control must be defined as ‘standalone’ in ngModelOptions.
Example 1: <input [(ngModel)]=“person.firstName” name=“first”>
Example 2: <input [(ngModel)]=“person.firstName” [ngModelOptions]="{standalone: true}">

再看下ngModelOptions的定义,它其实是ngmodel指定的一个input属性,当standalone值为true时,代表着此 ngModel 不会把自己注册进它的父表单中,其行为就像没在表单中一样。
image

我们项目中使用ngModel其实是属于Template-driven Form,但shark中其实并没有用到ng的form表单校验。而Angular 会在 <form> 标签上自动创建并附加一个 NgForm 指令,NgForm 指令为 form 增补了一些额外特性。 它会控制那些带有 ngModel 指令和 name 属性的元素,监听他们的属性(包括其有效性)。 它还有自己的 valid 属性,这个属性只有在它包含的每个控件都有效时才是真。

forms/src/directives/ng_model.ts:

/**
   * @description
   * Tracks the name bound to the directive. The parent form
   * uses this name as a key to retrieve this control's value.
   */
  // TODO(issue/24571): remove '!'.
  @Input() name !: string;

forms/src/directives/ng_form.ts:

/**
   * @description
   * Method that sets up the control directive in this group, re-calculates its value
   * and validity, and adds the instance to the internal list of directives.
   *
   * @param dir The `NgModel` directive instance.
   */
  addControl(dir: NgModel): void {
    resolvedPromise.then(() => {
      const container = this._findContainer(dir.path);
      (dir as{control: FormControl}).control =
          <FormControl>container.registerControl(dir.name, dir.control);
      setUpControl(dir.control, dir);
      dir.control.updateValueAndValidity({emitEvent: false});
      this._directives.push(dir);
    });
  }

可以看到Angular 创建了一些 FormControl,并把它们注册到 Angular 附加到 <form>标签上的 NgForm 指令。 注册每个 FormControl 时,使用name属性值作为键值。
所以每个form中的input元素的name值必须是唯一的,或者使用[ngModelOptions]="{standalone: true}"将其排除在表单之外。

那么ng表单和表单验证是什样的?

二、ng表单和表单验证 (https://angular.cn/guide/forms-overview)

ng中一个重要的概念就是表单,ng提供了响应式表单(Reactive Form)和模板驱动表单(Template-driven form)两种形式。这两种形式的表单都基于几个共同的底层概念:

  • FormControl 实例用于追踪单个表单控件的值和验证状态。
  • FormGroup 用于追踪一个表单控件组的值和状态。
  • FormArray 用于追踪表单控件数组的值和状态。
  • ControlValueAccessor 用于在 Angular 的 FormControl 实例和原生 DOM 元素之间创建一个桥梁。
2.1 目前Angular中提供的内置验证器有
class Validators {
  static min(min: number)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular 表单验证是一种在 Web 应用程序中对用户输入进行验证的方法。它可以防止用户在提交表单之前输入不正确的数据。在 Angular 中,表单验证是通过构建验证器函数并将其应用于表单控件来完成的。以下是一个简单的例子,演示如何在 Angular 中应用表单验证: 1. 在 HTML 模板中定义表单: ```html <form (ngSubmit)="onSubmit()" #myForm="ngForm"> <label> Name: <input type="text" name="name" ngModel required> </label> <label> Email: <input type="email" name="email" ngModel required email> </label> <button type="submit" [disabled]="!myForm.form.valid">Submit</button> </form> ``` 2. 在组件中定义验证器函数: ```typescript import { Component } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.css'] }) export class FormComponent { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ name: ['', Validators.required], email: ['', [Validators.required, Validators.email]] }); } onSubmit() { console.log(this.myForm.value); } } ``` 在上面的代码中,我们使用 `FormBuilder` 创建了一个名为 `myForm` 的表单,并添加了两个控件:`name` 和 `email`。`name` 控件是必填的,而 `email` 控件则需要符合电子邮件格式。在 `onSubmit` 方法中,我们可以访问表单的值,并进行进一步的处理。 值得注意的是,为了让表单控件与模板中的 `ngModel` 指令进行绑定,我们需要在组件中导入 `FormsModule` 模块。在模板中,我们还使用了 Angular 的模板语法,如 `ngSubmit` 事件和 `[disabled]` 属性,来控制表单的行为。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值