angular9的学习(十一)表单

from 表单特殊的点

formData1 = new FormGroup({
    firstName: new FormControl("Kevin"),
    lastName: new FormControl("Yang"),
});

console.log(formData1.value); // {firstName: 'Kevin', lastName: 'Yang'}

=================================================
formData1 = new FormGroup({
    firstName: new FormControl({value:"Kevin", disabled: true}),
    lastName: new FormControl("Yang"),
});

console.log(formData1.value); // {lastName: 'Yang'}
console.log(formData1.getRawValue()); // {firstName: 'Kevin', lastName: 'Yang'}   

=================================================
formData1 = new FormGroup({
    firstName: new FormControl({value:"Kevin", disabled: true}),
    lastName: new FormControl("Yang"),
});
formData1.disable();
console.log(formData1.value); // {firstName: 'Kevin', lastName: 'Yang'}   

==================================================
formData1 = new FormGroup({
    firstName: new FormControl({value:"Kevin", disabled: true}),    
}); 
console.log(formData1.value); // {firstName: 'Kevin'}

FormGroup的valueChanges

每当子控件的值更改时,都会触发valueChanges 事件

app.module.ts

import { FormsModule,ReactiveFormsModule } from '@angular/forms';

 imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,// +
    HttpClientModule,
    BrowserAnimationsModule,
    ReactiveFormsModule // +
  ],
export class ComponentOneComponent implements OnInit, AfterViewInit, OnDestroy {
  public fromDate1: FormGroup;
  constructor(private fb: FormBuilder) {  }
  onSubmit() {
    console.log(this.fromDate1);
  }
  ngOnInit(): void {
    this.fromDate1 = this.fb.group({
      firstName: ['', [Validators.required]]
    })
    this.fromDate1.get('firstName').valueChanges.subscribe(res=>{
      console.log(res);
    })
      // 查询某个值
      this.fromDate1.get('firstName').value
  }
}

html

修改某个值,也不会触发valueChanges事件

      this.fromDate1.get('firstName').setValue('xxxxxx',{emitEvent:false})

修改某个值,不会触发本身的valueChanges事件,但是父级的还是会触发

 this.fromDate1.get('firstName').valueChanges.subscribe(res=>{
      console.log(res);// 不会触发
    })
    this.fromDate1.valueChanges.subscribe(res=>{
      console.log(res);// 会触发
    })
    setTimeout(()=>{
      this.fromDate1.get('firstName').setValue('xxxxxx',{ onlySelf: true })
    },5000)

验证状态

firstName.errors 取得栏位验证错误讯息,若验证通过回传null
firstName.dirty 如果值修改了则为true
firstName.touched 如果值被触动则为true
firstName.valid 如果通过所有验证则为true

formBuilder.Array

export class ComponentOneComponent implements OnInit, AfterViewInit, OnDestroy {
  public fromDate1: FormGroup;

  constructor(private fb: FormBuilder) {}
  // 获取表单的数组
  get citiesArr(): FormArray {
    return this.fromDate1.get('cities') as FormArray;
  }

  //删去
  removeAttr(index): void {
    this.citiesArr.removeAt(index)
  }

  // 添加
  get addList(): FormGroup {
    return this.fb.group({
      one: ['', [Validators.required]],
      two: ['', [Validators.required]]
    })
  }

  addListGroup(): void {
    this.citiesArr.push(this.addList)
  }

  onSubmit() {
    console.log(this.fromDate1);
  }

  ngOnInit(): void {
    this.fromDate1 = this.fb.group({
      firstName: ['', [Validators.required]],
      lastName: ['', [Validators.required]],
      cities: this.fb.array([
        this.fb.group({
          one: ['', [Validators.required]],
          two: ['', [Validators.required]]
        })
      ])
    })
  }
}

=====
      os_list: {
    [index: number]: {
      os: string,
      os_version: string,
    }
  },
  soft_list: {
    [index: number]: {
      vendor: string,
      software_name: string,
      software_type: string,
      software_version: string
    }
  },

html

添加

删除

提交的时候,如果没有校验成功就禁用

[disabled]="!validateForm.valid"  

重置表单

fromDate1.reset()

setValue和pathValue区别

在 FormArray中
myFormArray = new FormArray([
  new FormControl(),
  new FormControl(),
  new FormControl()	
])
this.myFormArray.setValue(["AA", "BB"]); 
会报错
但是使用 patchValue
ngOnInit() {
   console.log(this.myFormArray.value);

   this.myFormArray.patchValue(["AA", "BB"]);
   console.log(this.myFormArray.value);

   this.myFormArray.reset();
	
   this.myFormArray.patchValue(["AA"]);
   console.log(this.myFormArray.value);
} 
[null, null, null]
["AA", "BB", null]
["AA", null, null] 

ng-zorro 动态表单

    
        
操作系统{{i+1}} 长度超过了8个字符 不能为空
this.validateForm = this.fb.group({
     os_list: this.fb.array([
        this.fb.group({
          os: [null, [Validators.required, Validators.maxLength(5)]],//操作系统
          os_version: [null, [Validators.required, Validators.maxLength(20)]],//版本
        })
      ]),
})

这个我们会遇到遍历每一个子节点状态的问题

  private submit(): void {
    if (!this.validateForm.valid) {
      this.markAsDirtyDeep(this.validateForm);
      return;
    }
    //submit
  }

  public markAsDirtyDeep(control: AbstractControl): void {
    if (!control) return;

    control.markAsDirty();

    if (control instanceof FormGroup) {
      const ctl = control;
      for (let inner in ctl.controls) {
        this.markAsDirtyDeep(ctl.get(inner));
      }
    } else if (control instanceof FormArray) {
      const ctl = control;
      for (let inner in ctl.controls)
        this.markAsDirtyDeep(ctl.get(inner));
    }
  }

记得表单开头别写submit不然按钮新增的时候会触发submit,把我坑惨了,昨晚没睡好觉

你可能感兴趣的:(angular9的学习(十一)表单)