angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Property 'controls' does not exist on type 'AbstractControl'.

Open shammelburg opened this issue 9 years ago • 37 comments

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Versions.

@Angular/cli: 1.0.1 node: 7.5.0 os: win32 x64 Windows (10)

Repro steps.

Running the application using ng serve works fine.

using ng build works fine.

when using ng build --prod --aot or ng build --prod I get the error.

It points back to this html file and the controls property??

<div formArrayName="Data">
    <div class="form-group" *ngFor="let field of form.get('Data').**controls**; let i = index">
        <div [formGroupName]="i">
            <div class="col-sm-2">
                <input type="text" class="form-control input-sm text-right" placeholder="Key" formControlName="Name" />
            </div>
            <div class="col-sm-6">
                <input type="text" class="form-control input-sm" placeholder="Value" formControlName="Data" autocomplete="off" />
            </div>
            <div class="col-sm-1">
                <i class="fa fa-trash-o cursor remove-field" title="Remove field" (click)="removeField(i)"></i>
            </div>
        </div>
    </div>
</div>

The log given by the failure.

ERROR in ng:///C:/Angular/lanes4/src/app/containers/edit-user.component.html (34,13): Property 'controls' does exist on type 'AbstractControl'.

Desired functionality.

I would like to build it using --prod and --aot

Mention any other details that might be useful.

Happened since updating to version 4.0.0, i've just been using ng build

shammelburg avatar Apr 27 '17 07:04 shammelburg

Why is this issue closed? Is this fixed in production builds now? Doesn't seem like it...

RPGillespie6 avatar Mar 21 '18 14:03 RPGillespie6

Running Angular 5.2.3 and was having the same problem. I have a nested FormGroup i.e.

// simplified
this.deviceForm = this.formBuilder.group({
  deviceName: '',
  advancedOptions: this.formBuilder.group({
    bridgeUrl: 'wss://api.my.site:443',
  }),
})
// this.deviceForm: FormGroup
// this.deviceForm.controls.advancedOptions: AbstractControl
// ^^ should really be type FormGroup
// this.deviceForm.controls.advancedOptions.controls.bridgeUrl
// ^^ ERROR 'controls' doesn't exist on type 'AbstractControl'

I found a few ways to get around this (thanks to y'all posting here). Assuming we have:

this.deviceForm.controls.advancedOptions.controls.bridgeUrl

We can:

1. Use .get():

this.deviceForm.get('advancedOptions')!.get('bridgeUrl')!
// Note the '!'s to tell TS to assume `get` result is non-null

2. Cast

(<FormGroup> this.deviceForm.controls.advancedOptions).controls.bridgeUrl

3. Use a custom class

// Define AbstractFormGroup
interface AbstractFormGroup extends FormGroup {
  controls: {
    [key: string]: AbstractControl & FormGroup & AbstractFormGroup,
  }
}
export class ... {
  deviceForm: AbstractFormGroup
}

// Note: This makes nested form groups (a.controls.b.controls.c... etc.)
// acceptable by the compiler, however this exposes both AbstractControl
// and FormGroup properties on all controls, so you can hit runtime errors
// if you try to use FormGroup properties when your control is just an
// AbstractControl and vice versa.

I ended up going with 1 as I think it's the cleanest

keego avatar May 22 '18 22:05 keego

This worked for me:

form.get('passwords').get('confirmPassword').dirty

mpro7 avatar Sep 20 '18 15:09 mpro7

This worked for me:

form.get('passwords').get('confirmPassword').dirty

This is not allowed by angular-tslint, because functions may fire multiple times

robvaneck avatar Oct 01 '18 09:10 robvaneck

Что работает для меня (даже используя флаг --prod), вместо использования элементов управления в FormArray я использую значение : *ngFor="let item of myForm.get('items').value"

Спасибо!!! Всё работает!!!

babtsoualiaksandr avatar Oct 13 '18 16:10 babtsoualiaksandr

In my case only ng build --prod was failing with - Property 'controls' does not exist on type 'AbstractControl'

I changed

<div *ngFor="let item of myForm.controls['keyName'].controls;let indx=index;let lst=last;" >

to

HTML:- <div *ngFor="let item of getControls(myForm, 'keyName');let indx=index;let lst=last;" > TS File:-

getControls(frmGrp: FormGroup, key: string) {
  return (<FormArray>frmGrp.controls[key]).controls;
}

It worked for me!

imvikaskohli avatar Dec 13 '18 10:12 imvikaskohli

CLI doesn't complain when ['controls'] property accessor is used.

Below worked for me

 <div formArrayName="formArray" *ngFor="let item of form.get('formArray')['controls']; let i = index;">
....

</div>

anikets43 avatar Jan 01 '19 21:01 anikets43

Please reopen the issue still occurs in Angular 5.2.0

StarpTech avatar Jan 12 '19 00:01 StarpTech

use safe navigation operator ? change: myForm.get('myField').controls

to: myForm.get('myField')?.controls

ebinmanuval avatar Feb 13 '19 04:02 ebinmanuval

for validation errors use...

<span *ngIf="f.YOUR_FORM_KEY.controls.YOUR_FORM_KEY.errors?.YOUR_FORM_VALIDATION">YOUR_FORM_KEY is YOUR_FORM_VALIDATION</span>

eg.

<span *ngIf="f.name.controls.name.errors?.required">Name is required</span>

ts file

get f(): any {
    return this.userForm.controls;
}

mhardaniel avatar Mar 09 '19 01:03 mhardaniel

This solution works for me myForm.get('<formGroupName>').get('<formControlName>').hasError('required')

samuelkavin avatar May 12 '19 12:05 samuelkavin

try this, it works for me *ngFor="let item of formGroup?.get('timings')?.controls; let i = index;"

<ng-container [formGroup]="providerService.providerFG">
  <ng-container formArrayName="contentSites" *ngFor="let site of providerService.providerFG.get('contentSites').value; let i = index">
    <ng-container [formGroupName]="i">
      <input formControlName="id">
      <app-content-site [idSite]="route.snapshot.paramMap.get('id')" [index]="i" *ngIf="isSiteActivated() && route.snapshot.paramMap.get('id') === providerService.providerFG.get(['contentSites', i]).get('id').value"></app-content-site>
    </ng-container>
  </ng-container>
</ng-container>

anonymous1983 avatar May 30 '19 18:05 anonymous1983

@anonymous1983 Using *ngFor="... form.get('foo').value" instead of *ngFor="... form.get('foo').controls" does fix the template error, but it introduces reinitialization of the components within the array. This means, within your nested form you can only type one character, then it loses focus, because the nested component is getting recreated (ngOnInit is getting called for every key stroke).

My form looks like this:

form = this.fb.group({
  foo: this.fb.array([{ x: '', y: '' }]),
});

Though i'd go for *ngFor="... form.get('foo')['controls'] to prevent the template error:

<form [formGroup]="form">
  <ng-container formArrayName="foo">
    <div *ngFor="let item of form.get('foo')['controls']; let i = index">
      <app-custom-control-value-accessor [formControlName]="i"></app-custom-control-value-accessor>
    </div>
  </ng-container>
</form>

benneq avatar Jun 03 '19 09:06 benneq

Got it!

Looked at the docs - FormArray

The FormArray class contains the controls property.

get formData() { return <FormArray>this.passwordForm.get('Data'); }

Thanks @Thisen, without you help it would've taken longer.

I'm using angular 8 at this moment and I've used get formData() { return this.passwordForm.get('Data') as FormArray; }

Vreyesm avatar Jun 29 '19 16:06 Vreyesm

La solucion mas facil es: formGroup.controls['any']['controls'].

thank you, gracias, this helped me!

cluzier avatar Jul 16 '19 19:07 cluzier

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.