角度6:错误TS2339:类型“ HTMLElement”上不存在属性“值”

时间:2018-10-27 09:36:13

标签: javascript angular html5 typescript angular6

我有textarea,允许用户提交评论,我想按时抓取评论提交的日期,并与添加的评论一起保存到json中:

在json文件中提交评论后,我想要这样的东西:

 "comment": [
    {
      "id": 1,
      "username": "Michael Ross",
      "city": "New York USA",
      "date": "2018-01-01T00:00:00",
      "task_id": 1,
      "description": "Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et lig"
    }
]

问题:现在提交评论时,我有以下内容:未显示日期:

 "comment": [
    {
      "id": 1,
      "username": "Michael Ross",
      "city": "New York USA",
      "task_id": 1,
      "description": "Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et lig"
    }
]

到目前为止,这是我尝试从输入的评论中获取日期的方法。

HTML:

<form class="add-comments" [formGroup]="addForm" (keyup.enter)="addComments()">
      <input type="hidden" id="localTime" name="localTime">
    <div class="form-group">
      <textarea class="form-control" rows="1" placeholder="Add comments" formControlName="description" id="description"></textarea>
    </div>
  </form>

这是组件ts上的方法。

 addComments(task_id) {
    const formData = this.addForm.value;
    formData.task_id = task_id;
    this.userService.addComments(formData)
    .subscribe(data => {
      this.comments.push(this.addForm.value);
    });
    const date = new Date();
    const d = date.getUTCDate();
    const day = (d < 10) ? '0' + d : d;
    const m = date.getUTCMonth() + 1;
    const month = (m < 10) ? '0' + m : m;
    const year = date.getUTCFullYear();
    const h = date.getUTCHours();
    const hour = (h < 10) ? '0' + h : h;
    const mi = date.getUTCMinutes();
    const minute = (mi < 10) ? '0' + mi : mi;
    const sc = date.getUTCSeconds();
    const second = (sc < 10) ? '0' + sc : sc;
    const loctime = month + day + hour + minute + year + '.' + second;

    document.getElementById('localTime').value = loctime;

  }

不幸的是,当我提交评论时,出现以下错误

ERROR in src/app/user-profile/user-profile.component.ts(75,21): error TS2365: Operator '+' cannot be applied to types 'string | number' and 'string | number'.
src/app/user-profile/user-profile.component.ts(77,42): error TS2339: Property 'value' does not exist on type 'HTMLElement'.

要获得我想要的东西我需要改变什么?

1 个答案:

答案 0 :(得分:2)

您可以尝试使用此代码

const loctime = `${year}-${month}-${day}T${hour}:${minute}:${second}`;
// output "2018-10-27T10:26:32"

尝试使用Angular方式,而不是使用Javascript方式

<input type="hidden" id="localTime" name="localTime" formControlName="localTime">

this. addForm.get('localTime').setValue(loctime);

注意:我们需要使用反引号(``)而不是单引号('')。