Reputation: 171
So I have 2 fields that can be filled in the UI
and it works but how can I fill the UI programmatically.
<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>
And in the .ts
file I have:
durationText : "";
pitchfile: any;
And i want to set it like:
durationText = "120";
But it does not let me so what should I do ?
And how do I set the file pitchfile
programmatically.
Upvotes: 2
Views: 12193
Reputation: 39432
There's an issue with your code.
durationText : "";
pitchfile: any;
Should have been:
durationText : string;
pitchfile: any;
In case this was a text file that you were accepting and the user selected the file via an input
type file, you could read the contents of it using this:
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);
}
...
}
The Sample StackBlitz is updated accordingly.
Not really sure how you'll be able to get the duration from a text file.
But if you have an actual audio file, you can do something like this:
You can create a new Audio()
instance and then set it's src
property using URL.createObjectURL($event.target.files[0]);
. Once the metadata is loaded, the Audio instance fires a loadedmetadata
event to which you can listen to assigning a function to the onloadedmetadata
on the audio instance.
Inside this callback function, you can check for the duration
property.
Give this a try:
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;
};
}
...
}
Here's a Working Sample Stackblitz for your ref.
Upvotes: 3
Reputation: 7630
This is very simple, you need to add 'name' attribute to your input like this:
<input type="text" class="form-control" [(ngModel)]="durationText" id="durationText" name="durationText" placeholder="Song Duration">
Upvotes: 1