【问题标题】:How to set type string | number for variable in typescript如何设置类型字符串 |打字稿中变量的编号
【发布时间】:2021-06-11 23:56:44
【问题描述】:

我正在尝试重置文本框的值。试图设置类型'string | number' 到变量,但我得到一个错误。那么如何在打字稿中将两种类型设置为单个变量。请帮助找到解决方案。

  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
       }
   }}

错误:

元素[i].value = values[i];

键入'字符串 | number' 不可分配给类型 'string'。 类型“数字”不可分配给类型“字符串”

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

【问题讨论】:

  • 它告诉你valuesstring | number 的数组,这意味着它可以同时包含字符串和数字——你不能将number 直接分配给string。根据您的用例,您可以安全地convert the number to a string though
  • @Chase:你能编辑我的 stackblitz 吗?

标签: typescript angular8 angular11


【解决方案1】:

我会使用响应式表单并使用以下方式:

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 }
  }
}

在你的模板中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多