[英]Setting value via DOM doesnt update the value of the input with ngModel using Angular
我試圖上傳一個文件來計算它的哈希值並將其放入輸入框中。 如果我這樣做正確,它應該在表單中顯示值,但如果我提交表單,則該值不會發送。 僅當我單擊輸入字段並添加一個空格時,例如:
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;
});
}
}
組件.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>
組件.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);
}
}
好吧,選擇使用 Angular(組件上的方法)而不是單獨的 Javascript 文件(因為在 dom 上搜索元素會出現問題(由於視圖封裝等 -> 即`querySelector('.className') - 不會\\t find elements) 等等 ) ,因此使用 Angular 的事件(不是 html native events = onchange => (change) ):
https://stackblitz.com/edit/angular-ivy-hkxojg?file=src%2Fapp%2Fapp.component.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.