简体   繁体   中英

How to change input label value programmaly using Angular

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.

UPDATE 1:

There's an issue with your code.

durationText : "";
pitchfile: any;

Should have been:

durationText : string;
pitchfile: any;

UPDATE 2:

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.


ORIGINAL ANSWER:

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.

这非常简单,您需要像这样在输入中添加“名称”属性:

<input type="text" class="form-control" [(ngModel)]="durationText" id="durationText" name="durationText" placeholder="Song Duration">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM