Angular 6中点击Create New时如何为每个卡片设置随机颜色
Got it, let's tackle this problem step by step. Here's how you can assign random colors to each app card when clicking the "Create New" button in your Angular 6 project:
Step 1: Add Random Color Logic in Your Component.ts
First, we'll add code to generate random colors (either from a curated palette for UI consistency, or fully random) and assign these colors to each item in your appList when the "Create New" button is clicked. We'll also initialize colors when the app list first loads so cards have colors right away.
Update your component.ts like this:
// Add a curated color palette (optional but recommended for better UI harmony) private colorPalette = [ '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9' ]; // Method to get a random color from the palette private getRandomColor(): string { const randomIndex = Math.floor(Math.random() * this.colorPalette.length); return this.colorPalette[randomIndex]; // Uncomment below for fully random hex colors if you prefer: // return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0'); } // Your existing openModal method - add color assignment here async openModal() { // Assign random color to each card when "Create New" is clicked this.appList.forEach(app => { app['cardColor'] = this.getRandomColor(); }); // Keep your existing modal opening logic here // ... (your original code for opening the modal) } // Update getApps to initialize colors when data loads async getApps() { const AppInfoData = Parse.Object.extend('w_appinfo'); const query = new Parse.Query(AppInfoData); try { this.appList = await query.descending("updatedAt").find(); // Initialize random colors for each app card on load this.appList.forEach(app => { app['cardColor'] = this.getRandomColor(); }); } catch (error) { this.toastr.error(error.message, 'Error!!!'); } }
Step 2: Update the Template to Bind Random Colors
Now modify your component.html to use the cardColor property we added, replacing the static class-based color assignment with dynamic style binding:
Find this line in your template:
<div [class]='"vimg rect-"+(i+1)'>
Replace it with:
<div class="vimg" [style.backgroundColor]="rlist?.cardColor">
Optional: Add Color to Card Borders
If you want the card borders to match the background color for a polished look, update the card container line too:
<div class="card card-box HYT" [style.borderColor]="rlist?.cardColor">
How This Works
- We use a curated color palette to avoid jarring color combinations (feel free to tweak the palette to match your app's theme).
- We add a custom
cardColorproperty to each app object inappList- this won't interfere with your existing Parse data structure. - Colors are initialized when the app list loads, and re-randomized every time the "Create New" button is clicked, exactly as you requested.
内容的提问来源于stack exchange,提问作者suhas wakhare

