【发布时间】:2022-01-05 17:04:12
【问题描述】:
谁能帮我解决这个问题。当表单变为有效时会发生这种情况,但随后我返回并初始化此组件(在 FormArray 中推送一个新值(从零项))。如何确定触发了哪个属性 ng-valid?是数组吗?数组中的单个元素?还是整个表单组?
我尝试过ngAfterContentChecked() { this.cdr.detectChanges(); } 和changeDetection: ChangeDetectionStrategy.OnPush,并在推送调用后调用this.cdr.detectChanges()。还是不行。这很奇怪,因为它只在表单第一次有效时发生,然后我添加了一个 an 元素。
@Component({
selector: 'app-list-other-conditions',
templateUrl: './list-other-conditions.component.html',
styleUrls: ['../survey-pmhx.component.scss']
})
export class ListOtherConditionsComponent implements OnInit, OnDestroy {
@Input()
formGroup!: FormGroup
@Input()
arrayName!: string
get formArray():FormArray {
return this.formGroup!.get(this.arrayName)! as FormArray
}
addItem() {
this.formArray.push(this.initItem())
}
removeItem(i:number) {
this.formArray.removeAt(i)
if (this.formArray.length === 0)
this.formArray.push(this.initItem())
}
public initItem = () : FormGroup =>
this.fb.group({
diagnosis: this.fb.control(null, Validators.required),
year: this.fb.control(null, [Validators.required, CustomValidators.pastYear])
})
constructor(private fb: FormBuilder, private readonly cdr: ChangeDetectorRef) { }
ngOnInit(): void {
if (this.formArray.length === 0)
this.addItem();
}
}
}
【问题讨论】:
-
你的代码formGroup和arrayName怎么样?类似于表单:FormGroup = this.fb.group ({ arrayName: this.fb.array ([]) }); y
-
没错,它在父组件中
<form [formGroup]="form"let myform = this.fb.group({ list: this.fb.array([]))})而这个子组件被称为<app-list-other-conditions [formGroup]="myform" arrayName="list"></... -
所以我不明白你为什么定义 arrayName !: string 因为它是一个数组,你可以上传父组件的代码和模板,所以我尝试执行它并查看你的问题。
-
我定义了arrayName,因为它是模板构建所需要的(更容易使用formArrayName)。
标签: angular angular-material angular-reactive-forms