angularangular-reactive-formsangular-testangular-testing-library

How to use input method in to ngFor loop form element


I am trying to add input value to *ngFor element. using ngFor i generate the table td's, which have the reactive form added.

here is my html:

<td *ngFor="let col of columns;" [ngClass]="col.class" data-testid="form-create-td">
<ng-container *ngIf="col.data !== ''">
   <input data-testid="form-create-name-field" id="name" type="text"
      class="form-control"
      formControlName={{col.data}}
      placeholder={{col.placeholder}}>
   <control-messages [control]="createForm.controls[col.data]"></control-messages>
</ng-container>
<ng-container *ngIf="col.data === ''">
   <button type="submit" aria-label="Ok" data-testid="form-create-btn" class="apply-item" style="border: 1px solid red"></button>
   <button type="button" aria-label="Cancel" (click)="confirmCancel(); false" class="cancel-apply"></button>
</ng-container>
</td>

from the above html, I am selecting the first td(data-testid="form-create-td[0]), and it's 1'st children ( form-create-name-field[0] ) and I am trying adding value to that as like follows:

expect(component.getAllByTestId('form-create-name-field')).toBeTruthy(); //works
const td = component.getAllByTestId('form-create-td')[0]; //works
component.fixture.detectChanges();

and trying to adding the value like : td.children[0] - is input element here

component.input(td.children[0], {
        target: {
            value: 'New name'
        }
    });

but not works.

I am setting the formControlName from ngFor. But I am not able to set it. if i console the td.children[0] - getting the following values:

HTMLUnknownElement {
        control: FormControl {
          validator: [Function],
          asyncValidator: null,
          _onCollectionChange: [Function],
          pristine: true,
          touched: false,
          _onDisabledChange: [ [Function] ],
          _onChange: [ [Function] ],
          _pendingValue: null,
          value: null,
          _updateOn: 'blur',
          status: 'INVALID',
          errors: { 'subsytem.required': true },
          valueChanges: EventEmitter {
            _isScalar: false,
            observers: [],
            closed: false,
            isStopped: false,
            hasError: false,
            thrownError: null,
            __isAsync: false
          },
          statusChanges: EventEmitter {
            _isScalar: false,
            observers: [],
            closed: false,
            isStopped: false,
            hasError: false,
            thrownError: null,
            __isAsync: false
          },
          _parent: FormGroup {
            validator: null,
            asyncValidator: null,
            _onCollectionChange: [Function],
            pristine: true,
            touched: false,
            _onDisabledChange: [],
            controls: [Object],
            valueChanges: [EventEmitter],
            statusChanges: [EventEmitter],
            status: 'INVALID',
            value: [Object],
            errors: null
          },
          _pendingDirty: false,
          _pendingTouched: false,
          _pendingChange: false
        }
      }

what is the correct approach to set the value to input element here?

UPDATE

when I have form field with validators object, I am not able to set the value. example i am not able to add value in following:

'Name': new FormControl('', { validators: [ValidationService.required, ValidationService.SubsystemMxLenght, ValidationService.SubsystemPatternMatch], updateOn: 'blur' }),
            'UpdatedByName': new FormControl({ value: this.appUserName, disabled: true }, []),

if I remove validators object and update like this:

'Name': new FormControl('', ),

works fine.


Solution

  • Have you tried selecting the input fields, instead of tds?

    component.input(component.getAllByTestId('form-create-name-field')[0], {
            target: {
                value: 'New name'
            }
        });
    

    Another way is to create test id's with an index, so you could do

    component.input(component.getByTestId('form-create-name-field-1'), {
            target: {
                value: 'New name'
            }
        });