The Event Parameter Binding in ANGULAR 6

The angular provided powerful feature to manipulate the DOM. Such as the *ngFor, a derective initializ the template once per item from an iterable. It is a very useful direcive. I use the ngFor directive to iterate every DIV and bind a click event with specific parameter. When I clicks different DIV, it should pass different parameter to the click event. And the test <a> tag will dispaly the paramters. But the issue is the test <a> tag only changed at the first time cilck.

Here is the HTML code:

The item div will be iterated output in the borwser. The variable ‘i’ stored the index of current datesArray. The variable “item” stored the date value which stored in the dateArray. The *ngFor directive will output the item with DIV.

Currently, I need each item div can react to click, so I add a click event in to each div. And I want the click event can recognize which div is clicked, so I passed parameters of array index and item.

Here is the srcipt code:

I can confirm the code is correct, and it will be called when the div is clicked.

But here is the issue. when the page was inilized, the div can react the click event. After the item div was clicked, it can not react any other click event.

In fact, this does not mean the dateClickEvent() didn’t react, the parameters also was passed in to the method at the second time click. The problem is every time when I use the ‘selctedDate’ array, the varialble ‘this.test’ will use the same reference of this array. That’s why everytime the test access the same value of the ‘selctedDate’ array.

Here is the corrected code. I redeclared the seletedDate array erverytime when the method is called. That will give the array a new reference. So the ‘test’ variable finds the new reference, it will be assign a new value.