[英]How can I change an input for a label without an error in value in Angular?
[英]How to change input label value programmaly using Angular
因此,我可以在UI
填充2个字段,并且它可以工作,但是如何以编程方式填充UI。
<div class="form-group">
<label for="durationText">Song Duration (ms)</label>
<input type="text" class="form-control" [(ngModel)]="durationText" id="durationText" placeholder="Song Duration">
</div>
<div class="form-group">
<label for="pitchfile">Pitches file (.txt)</label>
<input type="file" class="form-control-file" id="pitchfile" accept=".txt" (change)="setPitchfile($event)">
</div>
在.ts
文件中,我有:
durationText : "";
pitchfile: any;
我想将其设置为:
durationText = "120";
但这不让我怎么办? 以及如何pitchfile
编程方式设置文件pitchfile
。
您的代码有问题。
durationText : "";
pitchfile: any;
本来应该:
durationText : string;
pitchfile: any;
如果这是您正在接受的文本文件,并且用户通过input
类型文件选择了该文件,则可以使用以下命令读取其内容:
import { Component } from '@angular/core';
@Component({...})
export class AppComponent {
durationText;
setPitchfile($event) {...}
readFromTextFile($event) {
const file = $event.target.files[0];
var reader = new FileReader();
reader.onload = function () {
console.log(reader.result);
};
reader.readAsText(file);
}
...
}
样本StackBlitz会相应更新。
不太确定如何从文本文件中获取持续时间。
但是,如果您有实际的音频文件,则可以执行以下操作:
您可以创建一个new Audio()
实例,然后使用URL.createObjectURL($event.target.files[0]);
设置它的src
属性URL.createObjectURL($event.target.files[0]);
。 一旦加载元数据,音频实例触发一个loadedmetadata
事件,你可以听的分配功能onloadedmetadata
上的音频实例。
在此回调函数中,您可以检查duration
属性。
试试看:
import { Component } from '@angular/core';
@Component({...})
export class AppComponent {
durationText = '';
setPitchfile($event) {
console.log($event.target.files);
const audio = new Audio();
audio.src = URL.createObjectURL($event.target.files[0]);
audio.onloadedmetadata = () => {
console.log(audio.duration);
this.durationText = audio.duration;
};
}
...
}
这是供您参考的工作样本Stackblitz 。
这非常简单,您需要像这样在输入中添加“名称”属性:
<input type="text" class="form-control" [(ngModel)]="durationText" id="durationText" name="durationText" placeholder="Song Duration">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.