我正在尝试将输入值添加到*ngFor
元素。使用ngFor
i 生成表 td,其中添加了反应形式。
这是我的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>
从上面的 html 中,我选择了第一个 td( data-testid="form-create-td[0]
),它是第一个孩子 ( form-create-name-field[0]
),我正在尝试为其添加值,如下所示:
expect(component.getAllByTestId('form-create-name-field')).toBeTruthy(); //works
const td = component.getAllByTestId('form-create-td')[0]; //works
component.fixture.detectChanges();
并尝试添加如下值: td.children[0] - is input element here
component.input(td.children[0], {
target: {
value: 'New name'
}
});
但不起作用。
我正在设置formControlName
from ngFor
。但我无法设置它。如果我控制台td.children[0]
- 获得以下值:
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
}
}
在这里将值设置为输入元素的正确方法是什么?
更新
当我有带有验证器对象的表单字段时,我无法设置该值。例如,我无法在以下方面增加价值:
'Name': new FormControl('', { validators: [ValidationService.required, ValidationService.SubsystemMxLenght, ValidationService.SubsystemPatternMatch], updateOn: 'blur' }),
'UpdatedByName': new FormControl({ value: this.appUserName, disabled: true }, []),
如果我删除验证器对象并像这样更新:
'Name': new FormControl('', ),
工作正常。