He estado tratando de hacer que mi renderUserList funcione cuando envío una nueva Persona a la matriz y la muestro en una fila de la tabla. Para probar que se procesa desde el principio, agregué una primera persona a la matriz desde el principio. Cuando registro en la consola la matriz y la función de representación, parecen funcionar. La matriz aumenta y el sitio se muestra de nuevo cuando "envío" algo. Sin embargo, mi página permanece vacía independientemente de lo que haga y solo la matriz parece funcionar según lo previsto, pero mi dom html no cambia en lo más mínimo.
class Person { public Firstname: string; public Lastname: string; constructor(Firstname: string, Lastname: string) { this.Firstname = Firstname; this.Lastname = Lastname; } } let people: Person[] = [ new Person("Peter", "Parker")] document.addEventListener("DOMContentLoaded", () => { renderUserList(people); document.getElementById("add-user").addEventListener("submit", (event) => { event.preventDefault(); const FormField: HTMLFormElement = document.getElementById("add-person") as HTMLFormElement const FirstNameInput: HTMLInputElement = document.getElementById("Firstname") as HTMLInputElement; const LastNameInput: HTMLInputElement = document.getElementById("Lastname") as HTMLInputElement; const FName: string = FirstNameInput.value; const LName: string = LastNameInput.value; if (FName && LName) { people.push(new Person(FName, LName)); renderUserList(people); FormField.reset(); } }) function renderUserList(userlist: Person[]): void { const peoplelist: HTMLElement = document.getElementById("peoplelist") for (let i: number = 0; i < userlist.length; i++) { peoplelist.innerHTML = ""; `<tr> <td class="p-3 table-font">${people[i].Firstname}</td> <td class="p-3 table-font">${people[i].Lastname}</td> <td> <button class="btn tablebutton delete-button list-button" data-idx="${i}"><i class="fas fa-trash-alt"></i></button>] <button type="button" class="btn tablebutton edit-button list-button" data-bs-toggle="modal" data-bs-target="#ModalWindow" data-idx="${i}"><i class="fas fa-user-edit"></i></button> </td> </tr>`; } } })¿Podría ser esto un error tipográfico? Hay una línea peoplelist.innerHTML = ""; justo encima de la cadena de plantilla que contiene el marcado <tr> . Apostaría a que se pretendía algo como lo siguiente.
function renderUserList(userlist: Person[]): void { const peoplelist: HTMLElement = document.getElementById("peoplelist"); for (let i: number = 0; i < userlist.length; i++) { peoplelist.innerHTML = `<tr> <td class="p-3 table-font">${people[i].Firstname}</td> <td class="p-3 table-font">${people[i].Lastname}</td> <td> <button class="btn tablebutton delete-button list-button" data-idx="${i}"><i class="fas fa-trash-alt"></i></button>] <button type="button" class="btn tablebutton edit-button list-button" data-bs-toggle="modal" data-bs-target="#ModalWindow" data-idx="${i}"><i class="fas fa-user-edit"></i></button> </td> </tr>`; } } Sin embargo, todavía hay un pequeño problema, porque la asignación de innerHTML interno dentro de un bucle reemplazará los contenidos anteriores, y terminará con solo la última persona renderizada. Puede crear el marcado en el bucle for antes de asignar todas las filas a peoplelist.innerHTML a la vez, o tal vez incluso buscar otras formas de manipulación DOM, como insertAdjacentHTML .
Además, aparte, es bueno tener en cuenta los posibles problemas de seguridad al representar las entradas del usuario como marcado. ¿Qué sucede si alguien ingresa un código como su nombre? ¿Podría representar las partes en las que no confía como texto sin formato (con textContent , por ejemplo)?