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
<form [formGroup]="fromDate1" (ngSubmit)="onSubmit()"> <div> <label for="firstName">first Name</label> <input formControlName="firstName"> </div> <button>提交</button> </form>
修改某个值,也不会触发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
<form [formGroup]="fromDate1" (ngSubmit)="onSubmit()">
<div>
<label for="firstName">first Name</label>
<input formControlName="firstName">
</div>
<div>
<label for="lastName">lastName</label>
<input formControlName="lastName">
</div>
<div (click)="addListGroup()">添加</div>
<div formArrayName="cities" *ngFor="let item of fromDate1.get('cities')?.value; let i = index">
<ng-container [formGroupName]="i">
<input formControlName="one"/><br>
<input formControlName="two">
<span (click)="removeAttr(i)">删除</span>
</ng-container>
</div>
<button>提交</button>
</form>
提交的时候,如果没有校验成功就禁用
[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 动态表单
<ng-container *ngFor="let project of validateForm.get('os_list').controls;let i=index;" [formGroupName]="i">
<div nz-col nzSpan="12">
<nz-form-item>
<nz-form-label [nzSpan]="8" nzRequired nzFor="os">
操作系统{{i+1}}
</nz-form-label>
<nz-form-control [nzSpan]="12">
<input nz-input formControlName="os" />
<nz-form-explain
*ngIf="project.get('os')?.dirty && project.get('os')?.errors">
<ng-container *ngIf="project.get('os').hasError('maxlength')">
长度超过了8个字符
</ng-container>
<ng-container *ngIf="project.get('os').hasError('required')">
不能为空
</ng-container>
</nz-form-explain>
</nz-form-control>
</nz-form-item>
</div>
</ng-container>
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 {
this.markAsDirtyDeep(this.validateForm);
if (!this.validateForm.valid) {
return;
}
//submit
}
public markAsDirtyDeep(control: AbstractControl): void {
if (!control) return;
control.markAsDirty();
if (control instanceof FormGroup) {
const ctl = <FormGroup>control;
for (let inner in ctl.controls) {
this.markAsDirtyDeep(ctl.get(inner));
}
} else if (control instanceof FormArray) {
const ctl = <FormArray>control;
for (let inner in ctl.controls)
this.markAsDirtyDeep(ctl.get(inner));
}
}
记得表单开头别写submit不然按钮新增的时候会触发submit,把我坑惨了,昨晚没睡好觉
决定自己的高度的是你的态度,而不是你的才能
记得我们是终身初学者和学习者
总有一天我也能成为大佬