getting Validators to work in nested components

24 views
Skip to first unread message

john.mb...@gmail.com

unread,
Mar 12, 2021, 5:42:06 AM3/12/21
to Angular and AngularJS discussion
Hi,

So, in my Angular reactive forms, I am binding my form control to my component and in each component I have the following:

```
public form: FormGroup = new FormGroup({
control: new FormControl('', [Validators.required, Validators.max(1)])
});
```
I have added this into select dropdown in my HTML: 

[ngClass]="{ 'is-invalid': control.touched && control.invalid }"

I am not seeing is-invalid, am I doing something wrong?

Todd Zmijewski

unread,
Mar 12, 2021, 6:01:24 AM3/12/21
to Angular and AngularJS discussion
Do you have a getter for the control?

control is not a property of the component. Either you need to create a getter or explicitly reference the control.

view:

form.get('control').touched && form.get('control').invalid

or

component class:

get control(): FormControl {
  return form.get('control');

Todd Zmijewski

unread,
Mar 12, 2021, 6:02:25 AM3/12/21
to Angular and AngularJS discussion
god darnit....

get control(): FormControl {
  return this.form.get('control');
}

Todd Zmijewski

unread,
Mar 12, 2021, 6:09:55 AM3/12/21
to Angular and AngularJS discussion
Typically the reason you see that in tutorials and what not is because getters are defined for the control.

Todd Zmijewski

unread,
Mar 12, 2021, 6:11:16 AM3/12/21
to Angular and AngularJS discussion
I also wouldn't recommend naming the control control. That is really confusing. What is the purpose/context of the control. Name it that. Not control.

Todd Zmijewski

unread,
Mar 12, 2021, 6:13:00 AM3/12/21
to Angular and AngularJS discussion
public form: FormGroup = new FormGroup({
doBetterAtNaming: new FormControl('', [Validators.required, Validators.max(1)])
});

get doBetterAtNaming(): FormControl {
  return this.form.get('doBetterAtNaming');

Todd Zmijewski

unread,
Mar 12, 2021, 6:17:11 AM3/12/21
to Angular and AngularJS discussion
I'm not intending to come as a smart a**. I apologize if that is the way I'm coming off. That is not my intention.
Reply all
Reply to author
Forward
0 new messages