gpt4 book ai didi

angular - 从父组件中的自定义 formControl 继承验证时,在 ControlValueAccessor 中不起作用

转载 作者:行者123 更新时间:2023-12-05 01:13:48 26 4
gpt4 key购买 nike

<mat-error>在子 ControlValueAccessor 组件中没有父组件的影响 formControl验证。

<!-- Parent component template -->
<app-unique-name-text-box [formControl]="categoryName"></app-unique-name-text-box>
// Parent Component ts
this.addCategoryForm = fb.group({
'categoryName': ['', Validators.compose([Validators.required, BlankSpaceValidator.validate])]
});
this.categoryName = this.addCategoryForm.controls['categoryName'];
<!-- Child component template -->
<mat-form-field class="example-full-width">
<input matInput placeholder="Name" [formControl]="uniqueNameControl" (blur)="onInputBlur()">
<mat-error *ngIf="errorState">Enter a unique name</mat-error>
</mat-form-field>
// Child component ts
import {Component, OnInit, Optional, Self} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, NgControl} from '@angular/forms';
import {distinctUntilChanged} from "rxjs/operators";

@Component({
selector: 'app-unique-name-text-box',
templateUrl: './unique-name-text-box.component.html',
styleUrls: ['./unique-name-text-box.component.scss']
})
export class UniqueNameTextBoxComponent implements OnInit, ControlValueAccessor {
uniqueNameControl: FormControl = new FormControl('');

onChanged: any = () => {};
onTouched: any = () => {};

constructor(@Optional() @Self() public ngControl: NgControl) {
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
this.uniqueNameControl.valueChanges.pipe(distinctUntilChanged()).subscribe(
val => this.setInputValue(val)
);
}

get errorState() {
return this.ngControl.errors !== null && !!this.ngControl.touched;
}

ngOnInit() {
}

registerOnChange(fn: any): void {
this.onChanged = fn;
}

registerOnTouched(fn: any): void {
this.onTouched = fn;
}

writeValue(obj: any = ''): void {
this.uniqueNameControl.patchValue(obj);
}

setInputValue(val = '') {
this.uniqueNameControl.patchValue(val);
this.onChanged(val);
}
}

我需要在这里添加一些额外的配置来制作<mat-error>吗?在父级上显示 formControl无效

最佳答案

您必须像这样手动将父控件验证器添加到子组件

试试这个:

 ngOnInit() {
const validators = this.ngControl.control.validator;
this.uniqueNameControl.setValidators(validators ? validators : null);
this.uniqueNameControl.updateValueAndValidity();
}

Example

关于angular - <mat-error> 从父组件中的自定义 formControl 继承验证时,在 ControlValueAccessor 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59693475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com