【问题标题】:Setting value via DOM doesnt update the value of the input with ngModel using Angular通过 DOM 设置值不会使用 Angular 使用 ngModel 更新输入值
【发布时间】:2021-12-07 02:34:38
【问题描述】:

我试图上传一个文件来计算它的哈希值并将其放入输入框中。如果我这样做正确,它应该在表单中显示值,但如果我提交表单,则不会发送值。仅当我单击输入字段并添加空格时,例如:

javascript 文件

function calculateHash(file, callback) {  
    let reader = new FileReader();
    reader.onload = function(event) {
      let file_sha256 = sha256(reader.result);
      callback(file_sha256);
    };
    reader.readAsArrayBuffer(file);
}

function calc(){
  let file = document.getElementById("fileInput").files[0];   
  if (file) {
    calculateHash(file, function(file_sha256) {
        document.getElementById("hash").value = file_sha256;
    });
  }   
}

Component.html

<form #verifyForm="ngForm" (ngSubmit) = "onClickSubmit(verifyForm.value)">
   <br> <br> 
   <div class = "form-group">
    <div class="col-sm-9">
        <input class="form-control-file" name="fileInput" id="fileInput" type="file" onchange="calc()">     
    </div> <br> 
    <label for = "hash"> Hashwert (sha256)</label><br>
    <input type = "text" id = "hash" name = "hash" class= "form-control" > <br>
    <label for = "txid"> Transaktions-ID</label><br>
    <input type = "text" id = "txid" name = "txid" class= "form-control" > <br> 
    </div>
    <button class = "btn btn-primary">Verifizieren</button>
</form>

Component.ts

import { Component} from '@angular/core';



@Component({
  selector: 'app-verify',
  templateUrl: './verify.component.html',
  styleUrls: ['./verify.component.css']
})
export class VerifyComponent{

  constructor() {}

  

  onClickSubmit(data: { txid: string; hash: string; }){
    alert("Entered txid : " + data.txid);
    alert("Entered hash : " + data.hash);
  }

}

【问题讨论】:

  • 嗨!欢迎 :) 您能否包含您所看到的错误/意外行为的文本输出或屏幕截图(如果无法提供文本)?这将帮助用户回答您的问题。

标签: javascript angular angular-ngmodel


【解决方案1】:

好吧,选择使用 Angular(组件上的方法)而不是单独的 Javascript 文件(因为在 dom 上搜索元素会出现问题(由于视图封装等 -> 即。`querySelector('.className') -不会找到元素)等等),因此使用 Angular 的事件(不是 html 原生事件 = onchange => (change)):
https://stackblitz.com/edit/angular-ivy-hkxojg?file=src%2Fapp%2Fapp.component.ts

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 2016-10-02
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2016-11-02
    • 2021-07-13
    相关资源
    最近更新 更多