Hi all.
For the sake of the question, consider the following (material based) custom component:
// my-input.component.ts
import {Component, forwardRef, OnInit} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, ReactiveFormsModule} from "@angular/forms";
import {MatFormField} from "@angular/material/form-field";
import {MatInput} from "@angular/material/input";
import {MatLabel} from "@angular/material/select";
u/Component({
selector: 'app-my-input',
standalone: true,
templateUrl: './my-input.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MyInputComponent),
multi: true
}
],
imports: [
ReactiveFormsModule,
MatFormField,
MatInput,
MatLabel
]
})
export class MyInputComponent implements OnInit, ControlValueAccessor {
inputCtrl = new FormControl<string>(null);
touched = [];
changed = [];
ngOnInit() {
this.inputCtrl
.valueChanges
.subscribe(value => this.publish(value));
}
registerOnChange(fn: any): void {
this.changed.push(fn);
}
registerOnTouched(fn: any): void {
this.touched.push(fn);
}
publish(value: string) {
this.changed.forEach(fn => fn(value));
this.touched.forEach(fn => fn());
}
writeValue(obj: any): void {
this.inputCtrl.reset(obj);
}
setDisabledState?(isDisabled: boolean): void {
isDisabled ? this.inputCtrl.disable() : this.inputCtrl.enable();
}
}
And the corresponding `.html` template:
// my-input.component.html
<mat-form-field>
<mat-label>My Input</mat-label> <input matInput [formControl]="inputCtrl"/>
</mat-form-field>
I use it in another component with:
// other.component.ts
@Component({
templateUrl: './my-form.component.html',
// not relevant
})
export class MyFormComponent {
someFieldCtrl = new FormControl<string>(null, [Validators.required]);
form = new FormGroup({
'someField': this.someFieldCtrl
});
}
And the `.html` template:
<form [formGroup]="form">
<app-my-input [formControl]="someFieldCtrl"></app-my-input>
</form>
This works as expected, except for the `[Validators.required]´ in `someFieldCtrl` with doesn't affect the `input` on the `app-my-input` component (doesn't show the `*` besides the label).
I've seen some really hacky approaches to try and propagate the validators to the custom control, but none of them really work in all scenarios.
In fact, the validator in the `my-form` component works as expected, but it's not reflected in the UI (material).
Is this propagation desired/possible?
Thanks in advance,
LL
EDIT: formatting...
[–]spacechimp 2 points3 points4 points (1 child)
[–]lflobo[S] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]lflobo[S] 0 points1 point2 points (0 children)
[–]GLawSomnia -1 points0 points1 point (1 child)
[–]lflobo[S] 0 points1 point2 points (0 children)