GumZ GumZ - 3 years ago 173
Javascript Question

Angular2+ Validate dynamic form on modal input injection

I have a form where you can add dynamic inputs. These inputs can be typed or you can add text from a modal by selecting a value.

When typing into the input the form gets validated, but selecting a value from the modal does not validate the form even though the input is filled out.

Here is a simplified version of my template:

// form.component.html
<form #filterForm="ngForm">
<tr *ngFor="let data of droppedData; let i = index">
<td><input type="text" required #moduleValue[i]="ngModel"></td>

<ul *ngFor="let data of ['value1', 'value2', 'value3']">
<li (click)="selectValue()">{{data}}</li>
<button type="button" (click)="useValue()">Use Value</button>

Imagine my logic works perfectly. Here is my JavaScript (TypeScript) code:

// form.component.ts
selectValue(): void {
this.selectedValues = [];
for (let value of this.selectedValues) selectedValues.push(value);

useValue(): void {
this.filterForm.nativeElement.getElementsByTagName('input')[dynamicValueIndex].value = this.selectedValues; // appends selectedValue to form



When I type into the input the form gets validated, but selecting a value from the modal and injecting that value into the form's input does not validate the form.

I wish Angular would allow me to set the form validity like
this.filterForm.valid = true
in my
method, but I get this error:
ERROR TypeError: Cannot set property valid of [object Object] which has only a getter

Let me know if you have any suggestions to magically validate my form. Thanks!

Answer Source

I was able to resolve this by using @ViewChild referencing #filterButton in the template and then playing with the disabled attribute in its nativeElement in my useValue() method.


@ViewChild('filterButton') filterButton: any;

// other code

private useValue(): void {
    // some more other code
    this.filterButton.nativeElement.disabled = false;


<button #filterButton type="button" (click)="useValue()">Use Value</button>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download