Reputation: 39118
I have custom component (which I'm satisfied with) and using it in a reactive form like this.
private init() {
const control4 = new FormControl("yy", Validators.pattern(".{2}"));
const control5 = new FormControl("zz", Validators.pattern(".{3}"));
this.form = new FormGroup({
c4: control4,
c5: control5
});
}
The error messaging takes place in the main component and I can access the errors there. However, I'd like to add some functionality to the custom component reacting to it being invalid.
<input id="c4" formControlName="c4">
<app-textbox formControlName="c5"></app-textbox>
One way to do so is to provide NG_VALIDATOR
marker in the decorator of app-textbox and push a reference to self. However, that will amend a validator to the one already provided in the main component's setup shown above. I googled but got nothing useful as most of hits drowned in the custom component and custom validator examples.
Is it possible to access the validator, the error raised or the regex used in the reactive form setup while in the scope of the custom control being reacted to?
@Component({ selector: 'app-textbox', ... ,
providers: [
//{ provide: NG_VALIDATOR, useExisting: forwardRef(() => ...), multi: true },
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => ...), multi: true }]
})
export class TextboxComponent implements OnInit, ControlValueAccessor {
...
private showMeTheStuff() {
// access the validator, regex or error raised
}
}
Upvotes: 1
Views: 1208
Reputation: 29335
this can be done by using the injector and the appropriate hooks, import Injector and NgControl and do this:
constructor(private injector: Injector) {}
ngAfterViewInit() {
const ctrl = this.injector.get(NgControl, null)
console.log(ctrl)
}
The ctrl there will be the form control directive assigned to your custom control. this may be form control name, a form control, or a formgroup, etc. you'll have to figure it out once there and handle the cases you're interested in (probably jsut form control and form control name). you'll have access to the control and it's methods / properties and any parent as well.
Alternatively, you can inject the ControlContainer:
constructor(private ctrl: ControlContainer) { }
probably wana mark as optional and all that though. this will give you the parent form group directive which has access to all the same things.
Upvotes: 3
Reputation: 1365
I know it's not the best approach but at least it's something:
If you want to have access to the FormGroup inside your custom component (child) just pass the MainComponent's FormGroup (this.form) to your custom component as an @Input... Then you will have access to the entire FormGroup API from your variable.
like <app-textbox [form]="form" formControlName="c5"></app-textbox>
and catching the MainComponent's form like @Input() form: FormGroup;
inside your child (TextBoxComponent)
Upvotes: 1