I'm just now learning Angular 10 after a long time in AngularJS. I have a working version of this code which does not set the sorted variable, but I'm using this code to learn why I cannot set the variable sorted within my sortById function. The code below produces an error at line 29: ERROR TypeError: Cannot set property 'sorted' of undefined.
Obviously I do not understand the this. concept within the Angular framework.
import { Component, OnInit } from '@angular/core';
import { APPLICATIONS } from '../mock-applications';
@Component({
selector: 'app-applications',
templateUrl: './applications.component.html',
styleUrls: ['./applications.component.scss'],
})
export class ApplicationsComponent {
data = APPLICATIONS;
sorted:number = 0;
constructor() {};
ngOnInit() {};
// this function is triggered onClick
sortById(){
// not sorted yet
if(this.sorted === 0 || this.sorted === 2 ){
this.data.sort(function (a, b) {
this.sorted = 1; // ERRROR HERE
console.log('asc');
return a.Id - b.Id;
});
// sorted
} else {
this.data.sort(function (a, b) {
this.sorted = 2;
console.log('desc');
return b.Id - a.Id;
});
}
console.log('sorted ' + this.sorted);
}
}