在子级 ControlValueAccessor 组件中的
<mat-error>
对父级 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
无效时显示吗?
providers
中注册自己作为控件值访问器,那么它就不是一个控件值访问器。请搜索“ControlValueAccessor example”以查找示例,并查找组件装饰器中的providers
声明。 - JB Nizet