How to add dynamic array index value in angular html page

Viewed 1514

I am new to angular I want to add dynamic array index value in html page. I tried different solution I am not getting a solutions. I am not getting any error as well.

I have create a array in typescript as shown below

my typescript

months : string[] = ['January','February','March','April','May','June','July','August','September','October','November','December'];

the above array I want to pass dynamic index value in html page. I tried but I am not getting the value.

I tried like this {{ months[ result.startDate.split('/')[1] ] }} . If i type static index value it is working.

html page

 <div class="row" style="width: 110%;" *ngFor="let result of allEvents">

              <p class="start-date" >{{ result.startDate.split('/')[0]  }} </p> <br><p  >{{  months[ result.startDate.split('/')[1]  ]  }} </p>

        </div>

result object I am getting

0:
_id: "5e8b033bd3d04a24db92288a"
name: "Casting call for kannada movie"
description: "Looking for:↵Female artist Age: 17-26↵Kids Age :4-12"
startTime: "6"
endTime: "21"
startDate: "04/04/2020"
endDate: "31/05/2020"
participant: []
userId: "5e536de00d691f6427bcaec1"
pageId: {profileImage: {…}, coverPage: {…}, isBlocked: false, softDelete: false, isVerified: true, …}
createdAt: "2020-04-06T10:23:55.874Z"
updatedAt: "2020-04-06T10:23:55.874Z"

please help me

thanks in advance

4 Answers

That why it is not working. You need to remove 0 from 04 before putting value in the month array.

Parse your index with parseInt before passing it in the month array.

Please see the example below. It is in core JS.

Let me know, If you want it in an angular format I will create a stackblitz example for you

var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var result = {};
result.startDate = "04/04/2020";
var key = parseInt(result.startDate.split('/')[1]);
console.log(months[key]);

Please check this link for an example in angular - Example

Try like this:

.html

<p class="start-date" > </p> <br><p>{{getMonthName(result.startDate) }} </p>

.ts

getMonthName(month) {
  return this.months[(parseInt(month.split("/")[1])-1)];
}

Working Demo

component.html

 <div> {{getMonthName(result.startDate) }} </div>

component.ts

getMonthName(date) {
    return this.months[(new Date(date).getMonth())]
  }

Another aproach is transfor your object so, startDate and endDate becomes Date

allEvents.forEach(x=>{
   x.startDate=new Date(x.startDate)
   x.endDate =new Date(x.endDate )
})

And use pipeDate

{{result.startDate| date:'MMM'}}
Related