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

2
  • 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 Commented Mar 14, 2021 at 14:51
  • @Chase: Can you edit my stackblitz? Commented Mar 14, 2021 at 15:00

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.