簡體   English   中英

角度6:錯誤TS2339:類型“ HTMLElement”上不存在屬性“值”

[英]Angular 6: error TS2339: Property 'value' does not exist on type 'HTMLElement'

我有允許用戶提交評論的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'.

我需要更改以獲得我想要的東西嗎?

您可以嘗試此代碼

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

代替使用Javascript方式,嘗試使用Angular方式

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

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

注意:我們需要使用反勾號(``)而不是單引號('')。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM