Currently, I am working on developing a simple table in Angular where specific functions are applied to modify the table based on different conditions. These include sorting the data upon pressing the sort button and adding salutations based on the gender.
For this project, the data is static and stored in a TypeScript object. Below is the data object being used in the table:
let employeesArray: Employee[] = [
{name: "mike", salary: 100, gender: "M"},
{name: "jason", salary: 400, gender: "M"},
{name: "robin", salary: 9000, gender: "M"},
{name: "beast", salary: 5000, gender: "M"},
{name: "jimmy", salary: 3000, gender: "M"},
{name: "morris", salary: 2000, gender: "M"}
];
export default employeesArray;
The following Angular code displays the table data:
<tr *ngFor="let employee of employeesArray">
<td>{{employee.name}}</td>
<td>{{employee.salary}}</td>
<td *ngIf="showGender;">{{employee.gender}}</td>
</tr>
Additionally, a button has been added to add salutations based on gender:
<button type="button" (click)="addSalutation()" class="btn btn-success mx-2">Add Salutation</button>
However, upon pressing the salutation button, it should revert the salutation addition in the data. Below is the implementation of the addSalutation function:
import employeesArray from '../Employees';
employees: Employee[] = [...employeesArray];
employeesTemp: Employee[] = [...employeesArray];
addSalutation(){
if(this.showSalutation){
this.showSalutation=false;
this.employees = employeesArray;
console.log("Temporary array in true:");
console.log(this.employeesTemp);
}
else{
this.showSalutation=true;
this.employees = this.employees.filter((employee) => {
if(employee.gender === "M"){
employee.name = "Mr." + employee.name;
}
else{
employee.name = "Ms." + employee.name;
}
return employee;
});
console.log("Temporary array in false:");
console.log(this.employeesTemp);
}
Two separate copies of the data are being used so that changes can be reverted by copying data from one set to another upon button press. However, changes made in employees also reflect in employeesTemp, causing confusion.
The console.log() output within the function can be viewed here: https://i.sstatic.net/A4KVju8J.png
The goal is to ensure that no changes occur in employeesTemp so that reversions can be easily made. This issue needs further investigation.