1.Angular 表单中常用的属性和方法及其用法

属性:

`value`:获取表单的当前值。
`valid`:判断表单是否有效。
`invalid`:判断表单是否无效。
`dirty`:判断表单是否已被修改。
`pristine`:判断表单是否未被修改。
`touched`:判断表单是否已被触碰。
`untouched`:判断表单是否未被触碰。
`errors`:获取表单的验证错误信息。
`pending`:判断表单是否处于异步验证中。

方法:

`setValue(value: any)`:设置表单的值。
`patchValue(value: any)`:部分更新表单的值。
`reset(value?: any, options?: {onlySelf?: boolean, emitEvent?: boolean})`:重置表单的值。
`markAsTouched(options?: {onlySelf?: boolean})`:将表单标记为已触碰。
`markAsUntouched(options?: {onlySelf?: boolean})`:将表单标记为未触碰。
`markAsDirty(options?: {onlySelf?: boolean})`:将表单标记为已修改。
`markAsPristine(options?: {onlySelf?: boolean})`:将表单标记为未修改。
`markAllAsTouched()`:将所有表单控件标记为已触碰。
`markAllAsUntouched()`:将所有表单控件标记为未触碰。
`disable(options?: {onlySelf?: boolean, emitEvent?: boolean})`:禁用表单。
`enable(options?: {onlySelf?: boolean, emitEvent?: boolean})`:启用表单。
`setErrors(errors: ValidationErrors, opts?: { emitEvent?: boolean })`:设置表单的验证错误。
`clearValidators()`: 清除验证规则
`setValidators([])`:添加新的验证规则

下面是一个简单的例子,展示如何使用表单属性和方法:


import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  formGroup: FormGroup;

  constructor() {
    this.formGroup = new FormGroup({
      name: new FormControl('', Validators.required),
      email: new FormControl('', [Validators.required, Validators.email]),
      age: new FormControl('', Validators.min(18))
    });
  }

  submitForm() {
    if (this.formGroup.valid) {
      console.log('表单提交成功');
      console.log(this.formGroup.value);
    } else {
      console.log('表单验证未通过');
      console.log(this.formGroup.errors);
    }
  }
  
  resetForm() {
    this.formGroup.reset();
  }
  
  touchForm() {
    this.formGroup.markAllAsTouched();
  }
}

        `FormControl` 有很多验证器可以使用,比如 `Validators.required`、`Validators.email` 和 `Validators.min`。`FormGroup` 是一个包含多个表单控件的分组。在组件的方法中,我们可以使用表单属性和方法来操作表单,比如在 `submitForm` 方法中,我们通过检查 `formGroup.valid` 属性来判断表单是否通过验证,并根据需要执行相应的逻辑。`resetForm` 方法用于重置表单的值,`touchForm` 方法用于将表单标记为已触碰。

2.setValue 和 patchValue 的区别

        在 Angular 的表单中,使用 setValue方法会触发表单控件的 valueChanges事件,但不会触发 onChange事件。而使用 patchValue方法既会触发 valueChanges事件,也会触发 onChange事件。

        当使用 setValue方法设置表单控件的值时,表单控件的 `valueChanges` 事件会被触发,允许你订阅该事件以侦听值的变化。

        当使用 patchValue方法来部分更新表单控件的值时,在更新之后,表单控件valueChanges和 onChange事件都将被触发。valueChanges事件允许你订阅值的变化,而onChange事件用于向外部传达更新的值。

        下面是一个例子,展示了如何使用 `setValue` 和 `patchValue` 方法以及相应的事件处理:


import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  nameControl: FormControl;
  ageControl: FormControl;

  constructor() {
    this.nameControl = new FormControl('');
    this.ageControl = new FormControl('');
    
    // 订阅值的变化
    this.nameControl.valueChanges.subscribe(value => {
      console.log('Name value changed:', value);
    });
    
    // 订阅表单控件的值和状态的变化
    this.ageControl.valueChanges.subscribe(value => {
      console.log('Age value changed:', value);
    });
    
    this.ageControl.statusChanges.subscribe(status => {
      console.log('Age status changed:', status);
    });
  }

  updateName() {
    this.nameControl.setValue('John');
  }
  
  updateAge() {
    this.ageControl.patchValue(25);
  }
}

       在 updateName方法中,我们使用setValue方法将nameControl的值设置为John。这将触发 nameControl的valueChanges事件。在 updateAge方法中,我们使用patchValue方法将ageControl的值部分更新为 25。这将触发 ageControl的valueChanges和statusChanges事件。

        总结一下,`setValue` 方法只触发 `valueChanges` 事件,而 `patchValue` 方法会触发 `valueChanges` 和 `onChange` 事件。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐