Boby
Boby

Reputation: 168

Angular convert date

I have an input field called month.

  <span>
        Month: <br />
        <input id="typeahead-basic" type="text" class="form-control month" />
    </span>

What I want to do is, if you type in 6 in the month field, it will automatically change to 06, if you type 2, it will change to 02. So everything from 1-9 should add a zero. Would be nice if I could implement this into the component.ts class. Thank you very much!

Edit: So what I did was: This in the component:

 checkMonth() {
    if (this.month < 1) {
        this.month = "01";
    } else if (this.month > 12) {
        this.month = 12;
    } else if (this.month < 10) {
        this.month = '0' + this.month;
    }
}

And this as the HTML code:

<input class="form-control hideSpinners" min=1 max=12 type="number" [(ngModel)]="month"
                (change)="checkMonth()"/>

Upvotes: 0

Views: 47

Answers (3)

user4676340
user4676340

Reputation:

slice with a negative value will do the trick just fine :

const input = document.querySelector('input[type="text"]#id');

input.addEventListener('blur', () => {
  input.value = input.value.length === 1 ? 
    `0${input.value}`.slice(-2) :
    input.value;
});
<input id="id" type="text" placeholder="Enter a numeric value">
<input type="text" placeholder="Enter a numeric value (HTML only)" onblur="this.value = this.value.length === 1 ? ('0' + this.value).slice(-2) : this.value">

Upvotes: 1

Zooly
Zooly

Reputation: 4787

Impossible with simple HTML.

What you can do is call a function onChange when your value changes.

<span>
    Month: <br />
    <input id="typeahead-basic" type="text" class="form-control month" onchange="addZero(this)"/>
</span>

In your component script

addZero(input) {
    if(input.value > 0 && input.value < 10) input.value = `0${input.value}`;
}

Example : http://jsfiddle.net/nrjw56sv/ (Vanilla JS) https://stackblitz.com/edit/angular-fr19pk (Angular)

Upvotes: 1

KCM78
KCM78

Reputation: 3

You could use the ngModel directive. So something like:

  <span>
        Month: <br />
        <input name="inputfield" #input [(ngModel)]="month" (input)="changeDate(month)" id="typeahead-basic" type="text" class="form-control month" />
    </span>

You'll need a public property in your component that matches the ngModel, so "month" in this case.

Then you'd just need to write a changeDate function that takes the ngModel value from the input field and adds the 0 to it, which is straight forward enough in vanilla javascript.

Upvotes: 0

Related Questions