技术问询:JS在HTML解析数组渲染span及Angular代码通用化改造
1. Rendering Span Elements from an Array with Vanilla JavaScript
No problem! Here's a straightforward way to take an array and generate a <span> for each element in your HTML:
First, set up a container in your HTML where the spans will live:
<div id="spanContainer"></div>
Then write your JavaScript to loop through the array and create elements:
// Your array of data const myArray = ["First item", "Second item", "Third item"]; // Get the container element from the DOM const container = document.getElementById("spanContainer"); // Loop through each element in the array myArray.forEach(item => { // Create a new span element const span = document.createElement("span"); // Set the text content of the span to the array item span.textContent = item; // Optional: Add a class for styling span.classList.add("custom-span-class"); // Append the span to the container container.appendChild(span); });
This will generate a separate <span> for every element in your array and add them all to the container. You can adjust the class or add other attributes as needed for styling.
2. Refactoring Angular Code to Dynamically Render Spans from an Array
Your original code is hardcoded for specific array indexes, which isn't scalable. The issue with your attempt is that *ngIf is for conditional visibility, not looping—you need Angular's *ngFor directive instead.
Here's how to rewrite it to automatically render a <span> for every element in the errorMessage.address array:
<div class="xx" *ngIf="message.address && errorMessage.address?.length"> <span class="helper" *ngFor="let error of errorMessage.address"> {{ error }} </span> </div>
Let me break down what's changed:
- Removed all the hardcoded index checks (
address[0],address[1]) - Used
*ngFor="let error of errorMessage.address"to loop through each element in the array - Added
errorMessage.address?.lengthto the parent*ngIfto make sure we only render the div if there are actually error messages to display (the?.is the safe navigation operator to avoid errors iferrorMessage.addressis undefined) - Dropped the
this.in template expressions—Angular templates automatically reference component properties without needing it
This will dynamically create a <span> for every entry in errorMessage.address, so you don't have to update the template if the array grows or shrinks.
内容的提问来源于stack exchange,提问作者annepic

