0

I am trying to reset the textbox values. Tried to set the type 'string | number' to the variable but I am getting an error. So how to set two types to a single variable in typescript. Please help to find the solution.

  resetFn() {
     var values = Object.values(this.selVal); 
     var elements = document.getElementsByTagName("input");
      for (var i = 0; i < elements.length; i++) {
       if (elements[i].type == "text") {
       elements[i].value = ""; 
       elements[i].value = values[i]; // getting error
       }
   }}

Error:

elements[i].value = values[i];

Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'

Demo: https://stackblitz.com/edit/angular-dzxsg4?file=src%2Fapp%2Fapp.component.ts

Sansara
  • 85
  • 3
  • 15
  • it's telling you that `values` is an array of `string | number`, that means it can contain both strings and numbers - you cannot assign a `number` to a `string` directly. Depending on your usecase, you can safely [convert the number to a string though](https://stackoverflow.com/q/32554624/10305477) – Chase Mar 14 '21 at 14:51
  • @Chase: Can you edit my stackblitz? – Sansara Mar 14 '21 at 15:00

1 Answers1

0

I would use Reactive forms and go for something like this:

export class AppComponent {
  name = "Angular";

  formGroup = new FormGroup({
    name: new FormControl('Test'),
    gender: new FormControl('Male'),
    id: new FormControl(1)
  });

  selVal = {
    name: "Test",
    gender: "Male",
    id: 1
  };

  resetFn() {
    this.formGroup.reset();
    // or
    this.formGroup.get('name').setValue('Test');
    this.formGroup.get('gender').setValue('Male');
    this.formGroup.get('id').setValue(0);
  }

  updateFn() {
    this.selVal = { ...this.formGroup.value }
  }
}

and in your template:

<tbody [formGroup]="formGroup">
    <tr *ngFor="let item of selVal | keyvalue">
      <td>{{item.key}}</td>
      <td><input type="text" [formControlName]="item.key"></td>
    </tr>
</tbody>
Ajvar1
  • 107
  • 8