In users.component.ts a list of users which have been retrieved from backend as a bundle of Jsons are mapped out in a table. I think they are mapped out using filter-service.service The API call from backend for the users is made in getUsersByRole in backend.service filtering them by role ict. In case I click the new button in users.component.html an empty form is opened to create a new user. The form code is in new-user.component. After all fields in the empty form have been filled out a POST API ( const endpoint = ${environment.systemBackendUrl}administration/admin;) needs to be called to add the new user to backend. The POST API needs to send a JSON object from the info from the form that looks like this: { "resourceType": "Practitioner", "extension": [ { "url": "http://example.com/fhir/StructureDefinition/firstLogin", "valueCode": "true" }, { "url": "http://example.com/fhir/StructureDefinition/code", "valueCode": "434334/0" } ], "active": true, "name": [ { "use": "official", "family": "Eftimoski", "given": [ "Bojan" ] } ], "telecom": [ { "system": "email", "value": "b.eftimoski@gmail.com", "use": "work" }, { "system": "phone", "value": "+1234567890", "use": "mobile" } ], "address": [ { "use": "billing", "text": "5711 DHAKA VW\nSAN ANTONIO, TX 782504630\nUS", "line": [ "5711 DHAKA VW" ], "city": "SAN ANTONIO", "state": "TX", "postalCode": "782504630", "country": "US" } ], "gender": "male" } In the case of clicking the edit button in users.component.html the same form needs to be opened but it needs to be automatically filled with the information of the already existing user. I think this can be done with the filter service but let me know. Since all the information about the users is being fetched from backend in users.component.ts, I don’t want to have to retrieve all users from back everytime I click edit. So on edit the info of the user being edited needs to be retrieved locally. To not have to call the full list of users, everytime edit is clicked, try passing user data from one component to the other locally, even if it is as a whole json. After the form is automatically filled out with the info of the existing user a PUT API (const endpoint = ${environment.systemBackendUrl}administration/admin;) needs to be called to update the existing user in backend. This API needs to receive a json object that looks like this (where the new data replaces the old one that were populated in the form): { "resourceType": "Practitioner", "id": "5497395", "meta": { "versionId": "2", "lastUpdated": "2024-09-23T05:33:57.000-04:00", "source": "#sQcsV9tUkmLQoJdY" }, "extension": [ { "url": "http://example.com/fhir/StructureDefinition/firstLogin", "valueCode": "false" }, { "url": "http://example.com/fhir/StructureDefinition/code", "valueCode": "434334/0" }, { "url": "http://example.com/fhir/StructureDefinition/password", "valueCode": " 2 𝑎 10$YOltVAj4wwKFW0ILt7SKxeSemd/wF2iXwse4KoSN3Om4758i839Ce" } ], "active": true, "name": [ { "use": "official", "family": "Eftimoski", "given": [ "Bojan" ] } ], "telecom": [ { "system": "email", "value": "b.eftimoski@gmail.com", "use": "work" }, { "system": "phone", "value": "+1234567890", "use": "mobile" } ], "address": [ { "line": [ "5711 DHAKA VW" ], "city": "SAN ANTONIO", "state": "TX", "postalCode": "782504630", "country": "US" } ], "gender": "male" } The post and put APIs need to be made in fetch-user-data.service. When we are in edit, the mail and country cannot be changed. PRINT OUT EVERY SINGLE ONE OF THE FILES I SENT YOU FULLY WITH COMMENTS NEXT TO ALL THE CHANGES YOU MADE and a title above each file you are editing. If no changes were made write that also I am a beginner programmer so write what you are doing in detail. backend.service.ts: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from '../../../environments/environment'; @Injectable({ providedIn: 'root' }) export class BackendService { constructor(private http:HttpClient) { } //Sends forgot password request forgotPassword(practitionerMail:string){ const headers = new HttpHeaders({ 'mail': practitionerMail, });; const endpoint = `${environment.systemBackendUrl}administrationAuth/forgotPassword`; return this.http.post<any>(endpoint,{},{ headers:headers }); } //Get Users by role getUsersByRole(role: string) { const endpoint = ${environment.systemBackendUrl}administration/users; const params = { role: role }; console.log('Calling API with role:', role); // Add this line return this.http.get<any[]>(endpoint, { params }); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// users.component.ts: import { Component, Input, OnInit, OnDestroy } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterLink } from '@angular/router'; import { User } from '../../models/user.model'; import { UserService } from '../../services/fetch-data/fetch-user-data.service'; import { FilterService } from '../../services/filter/filter-service.service'; import { Subscription } from 'rxjs'; import { BackendService } from '../../services/backend/backend.service'; // Import BackendService @Component({ selector: 'app-users', standalone: true, imports: [CommonModule, RouterLink], templateUrl: './users.component.html', styleUrls: ['./users.component.scss'] }) export class UsersComponent implements OnInit, OnDestroy { @Input() isMenuOpen: boolean = false; users: User[] = []; filteredUsers: User[] = []; private subscriptions: Subscription[] = []; constructor( private userService: UserService, private filterService: FilterService, private backendService: BackendService // Inject BackendService ) { } ngOnInit(): void { this.loadUsers(); this.subscribeToFilters(); } // Load users from the backend service loadUsers() { const role = 'ict'; // Example role, replace with the role you want to use this.backendService.getUsersByRole(role).subscribe(users => { this.users = this.mapUsers(users); this.applyFilters(); // Apply filters initially }, (error) => { console.error('Error fetching users:', error); }); } // Map the raw data from the backend to the User model mapUsers(users: any[]): User[] { return users.map(user => ({ id: user.id, email: user.telecom.find((t: { system: string; }) => t.system === 'email')?.value || '', name: user.name[0]?.given.join(' ') || '', surname: user.name[0]?.family || '', phone: user.telecom.find((t: { system: string; }) => t.system === 'phone')?.value || '', state: user.address[0]?.state || '', city: user.address[0]?.city || '', country: user.address[0]?.country || '', line: user.address[0]?.line || [], status: user.active })); } // Subscribe to filter changes subscribeToFilters() { this.subscriptions.push( this.filterService.searchEmail$.subscribe(email => { this.applyFilters(); }) ); this.subscriptions.push( this.filterService.searchStatus$.subscribe(status => { this.applyFilters(); }) ); // Add subscription for searchName$ this.subscriptions.push( this.filterService.searchName$.subscribe(name => { this.applyFilters(); }) ); } // Apply filters to the list of users applyFilters() { let searchEmail: string = ''; let searchStatus: string = ''; let searchName: string = ''; // Add name variable // Fetch the latest filter values this.filterService.searchEmail$.subscribe(email => { searchEmail = email; }); this.filterService.searchStatus$.subscribe(status => { searchStatus = status; }); // Fetch the latest name filter value this.filterService.searchName$.subscribe(name => { searchName = name; }); // Filter users based on email, status, and name or surname this.filteredUsers = this.users.filter(user => (searchEmail === '' || user.email.toLowerCase().includes(searchEmail.toLowerCase())) && (searchStatus === '' || (searchStatus === 'active' ? user.status : !user.status)) && (searchName === '' || ( (user.name && user.name.toLowerCase().includes(searchName.toLowerCase())) || // Check if user.name exists (user.surname && user.surname.toLowerCase().includes(searchName.toLowerCase())) // Check if user.surname exists )) ); console.log("Filtered users: ", this.filteredUsers); } // Sorting method for admin table sortData(column: string, direction: string) { const sortMultiplier = direction === 'asc' ? 1 : -1; this.filteredUsers.sort((a, b) => { if (column === 'phone') { // Ensure phone values are numbers for numerical sorting const phoneA = Number(a.phone); const phoneB = Number(b.phone); // Check if conversion was successful if (isNaN(phoneA) || isNaN(phoneB)) { return 0; // If either phone is not a number, consider them equal } return (phoneA - phoneB) * sortMultiplier; } else if (column === 'status') { // Custom sorting for status return (a.status === b.status) ? 0 : (a.status ? -1 : 1) * sortMultiplier; } else { // Alphabetical sorting for email, name, and address const valueA = this.getColumnValue(a, column).toLowerCase(); const valueB = this.getColumnValue(b, column).toLowerCase(); return valueA.localeCompare(valueB) * sortMultiplier; } }); } // Helper method to get column value getColumnValue(user: User, column: string): string { switch (column) { case 'email': return user.email || ''; case 'name': return ${user.name || ''} ${user.surname || ''}; case 'address': return ${user.line ? user.line.join(' ') : ''} ${user.city || ''} ${user.state || ''} ${user.country || ''}.trim(); default: return ''; } } // Cleanup subscriptions to avoid memory leaks ngOnDestroy() { // Unsubscribe from subscriptions to avoid memory leaks this.subscriptions.forEach(sub => sub.unsubscribe()); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// users.component.html: Users NEW <th> Phone </th> <th> <button (click)="sortData('phone', 'asc')">▲</button> <button (click)="sortData('phone', 'desc')">▼</button> </th> <th> Address </th> <th> <button (click)="sortData('address', 'asc')">▲</button> <button (click)="sortData('address', 'desc')">▼</button> </th> <th> Status </th> <th> <button (click)="sortData('status', 'asc')">▲</button> <button (click)="sortData('status', 'desc')">▼</button> </th> <th></th> </tr> </thead> <tbody> <tr *ngFor="let user of filteredUsers"> <td>{{ user.name }} {{ user.surname }}</td> <td>{{ user.email }}</td> <td>{{ user.phone }}</td> <td> <ng-container *ngIf="user.line || user.city || user.state || user.country"> {{ user.line?.join(' ') }} <ng-container *ngIf="user.city"> <span *ngIf="user.line && user.line.length">, </span>{{ user.city }} </ng-container> <ng-container *ngIf="user.state"> <span *ngIf="user.city || (user.line && user.line.length)">, </span>{{ user.state }} </ng-container> <ng-container *ngIf="user.country"> <span *ngIf="user.state || user.city || (user.line && user.line.length)">, </span>{{ user.country }} </ng-container> </ng-container> </td> <td>{{ user.status ? 'Active' : 'Inactive' }}</td> <td> <button class="mb-2 me-2 tn-transition btn btn-outline-primary" [routerLink]="['/editAdmin', user.id]"> <i class="fa fa-pencil-alt me-1"></i> Edit </button> </td> </tr> <tr *ngIf="filteredUsers.length === 0"> <td colspan="6" class="text-center">No users found.</td> </tr> </tbody> </table> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// new-user.component.ts: import { Component, Input, OnInit } from '@angular/core'; import { MainLayoutComponent } from '../../Layout/main-layout/main-layout.component'; import { UsersComponent } from '../users/users.component'; import { CommonModule } from '@angular/common'; import { State, usStates } from '../../app-data/states'; import { StateSelectComponent } from '../../Layout/Components/state-select/state-select.component'; import { ActivatedRoute, Router } from '@angular/router'; import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { User } from '../../models/user.model'; import { UserService } from '../../services/fetch-data/fetch-user-data.service'; import { state } from '@angular/animations'; @Component({ selector: 'app-new-user', standalone: true, imports: [MainLayoutComponent, UsersComponent, CommonModule, StateSelectComponent, FormsModule, ReactiveFormsModule], templateUrl: './new-user.component.html', styleUrls: ['./new-user.component.scss'] }) export class NewUserComponent implements OnInit { @Input() origin: string = ''; // Track where the user is coming from states: State[] = usStates; selectedPhoneCode: string = ''; heading: string = 'New Admin'; userForm: FormGroup; users!: User[] ; @Input() showSearchFields: boolean = true; constructor(private fb: FormBuilder, private route: ActivatedRoute,private router: Router, private userService: UserService) { this.userForm = this.fb.group({ name: ['', [Validators.required, Validators.maxLength(100)]], surname: ['', [Validators.required, Validators.maxLength(100)]], email: ['', [Validators.required, Validators.email, Validators.maxLength(100)]], phone: ['', [Validators.required]], city: ['', [Validators.required, Validators.maxLength(100)]], line: ['', [Validators.required, Validators.maxLength(100)]], country: ['US', [Validators.required]], state: ['', [Validators.required]], gender: ['', [Validators.required]], status: ['', [Validators.required]] }); this.userService.getUsers().subscribe(users => { this.users = users; // Fetch users from service }); } ngOnInit() { this.route.data.subscribe(data => { if (data['origin'] === 'edit') { this.heading = 'Edit Admin'; this.populateUserForm(); } else { this.heading = 'New Admin'; } this.origin = data['origin']; }); } populateUserForm() { const userId = this.route.snapshot.paramMap.get('id'); const user = this.users.find(u => u.id === userId); if (user) { this.userForm.patchValue({ name: user.name, surname: user.surname, email: user.email, phone: user.phone, city: user.city, state: user.state, status: user.status, gender: user.gender, country: user.country, line: user.line }); this.selectedPhoneCode = user.phone; } } onStateChange(stateKey: string) { this.selectedPhoneCode = this.getPhoneCode(stateKey); // Update the phone form control with the selected phone code const phoneControl = this.userForm.get('phone'); if (phoneControl) { phoneControl.setValue(this.selectedPhoneCode); } } private getPhoneCode(stateKey: string): string { const state = this.states.find(s => s.key === stateKey); return state ? (${state.phoneCode}) : ''; } formatPhoneNumber(event: Event): void { const input = event.target as HTMLInputElement; let value = input.value.replace(/\D/g, ''); // Remove all non-digit characters if (value.length > 3 && value.length <= 6) { value = `(${value.slice(0, 3)})-${value.slice(3)}`; } else if (value.length > 6) { value = `(${value.slice(0, 3)})-${value.slice(3, 6)}-${value.slice(6, 10)}`; } else { value = `(${value}`; } input.value = value; } navigateBack() { this.router.navigate(['/home']); } saveUser() { if (this.userForm.valid) { // Save user logic here console.log(this.userForm.value); this.navigateBack(); } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// User model in frontend: // src/app/models/user.model.ts export interface User { id: string; email: string; name: string; status: boolean; phone: string; surname?: string; state?: string; city?: string; gender?: string; country?: string; line?: string[]; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// fetch-user-data.service.ts: import { Injectable } from '@angular/core'; import { User } from '../../models/user.model'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UserService { private users: User[] = []; constructor() {} setUsers(users: User[]): void { this.users = users; } getUsers(): Observable<User[]> { // Simulate async data fetching return of(this.users); // Example using RxJS 'of' to return observable } getUserById(id: string): User | undefined { return this.users.find(user => user.id === id); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Filter-service.service.ts: import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class FilterService { private searchEmailSubject = new BehaviorSubject(''); searchEmail$: Observable = this.searchEmailSubject.asObservable(); private searchStatusSubject = new BehaviorSubject(''); searchStatus$: Observable = this.searchStatusSubject.asObservable(); private searchNameSubject = new BehaviorSubject(''); searchName$: Observable = this.searchNameSubject.asObservable(); constructor() {} setSearchEmail(email: string) { console.log("setSearchEmail in fitler-service called"); this.searchEmailSubject.next(email); console.log("this.searchEmailSubject: "+this.searchEmailSubject.next(email)); } setSearchStatus(status: string) { if(status != this.searchStatusSubject.value){ this.searchStatusSubject.next(status); } } setSearchName(name: string) { if(this.searchNameSubject.value != name) { this.searchNameSubject.next(name); console.log("setSearchName called in filter-service " + this.searchNameSubject); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// The user model in angular – user.model.ts: // src/app/models/user.model.ts export interface User { id: string; email: string; name: string; status: boolean; phone: string; surname?: string; state?: string; city?: string; gender?: string; country?: string; line?: string[]; } Name and Surname	▲ ▼	Email	▲ ▼