![](/img/trans.png)
[英]How to send input from forms in html to javascript to my json file
[英]How to use JSON file from HTML input in Angular 8?
在我當前的 Angular 8 項目中,我有兩個 JSON 文件,它們應該連接到一個 JSON 數組。 然后應該導出新文件。
在谷歌搜索了很長時間后,我沒有找到如何使用兩個 JSON 文件的解決方案,我通過兩個 HTML 輸入調用這兩個文件,以便我可以在 Angular 組件中組合這兩個文件以形成一個 JSON 數組,其中包含來自兩者的輸入JSON 文件。
我目前的代碼:
JsonConverterComponent.html
<div class="form-group">
<label for="Json1">Json 1</label>
<input [(ngModel)]="json1" type="file" id="Json1" required>
</div>
<div class="form-group">
<label for="Json2">Json 2</label>
<input [(ngModel)]="json2" type="file" id="Json2" required>
</div>
<button [buttonLabel]="buttonNameJson" [disableCheck]="!json1 || !json2" (click)="combineJSON()"></button>
JsonConverterComponent.TS
export class JsonConverterComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit() {
}
buttonNameJson = "Combine JSON";
json1: File;
json2: File;
test: File;
one = this.json1;
two = this.json2;
public combineJSON() {
this.test = this.one;
console.log(this.test);
}
}
如果我只想調用兩個導入的 JSON 文件之一的內容,我總是收到錯誤“未定義”。
我必須做什么才能在 JsonConverterComponent.ts 中使用單個 JSON?
ngModel
指令不能用於類型為file
的input
,您必須像這樣對change
事件做出反應:
<input (change)="onFileChange($event)" type="file" id="Json1" required>
<input (change)="onFileChange($event)" type="file" id="Json2" required>
然后在 TypeScript 文件中:
onFileChange(event){
const fileToLoad = event.target.files[0];
const fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
const textFromFileLoaded = fileLoadedEvent.target.result;
const json = JSON.parse(textFromFileLoaded);
console.log(json);
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.