首页 > 解决方案 > Angular:样式或类绑定、座位图

问题描述

我正在为我的研究生学习项目而苦苦挣扎。我需要在 Angular 中制作交互式座位图,最多选择 9 个座位。在浏览了我以前的课程后,我能够在 JS 中创造一些魔法,但没有最大选择(链接到下面的 codepen)。

HTML 代码包含巨大的 SVG 图形 - 您可以在下面附加的 codepen 中找到它

CSS

.occupied {
    fill: red;
}

.free {
    fill: #afafaf;
}

Javascript

const buttonArray = document.querySelectorAll("#seats path");
console.log("query", typeof buttonArray);


var myArray = Array.from(buttonArray);
console.log(myArray);

for (let i = 0; i < myArray.length; i++) {
    myArray[i].setAttribute("id", `seat_${i + 1}`);

    document.getElementById(`seat_${i + 1}`).addEventListener("click", function() {
        if (document.getElementById(this.id).getAttribute("class") == "occupied") {
            document.getElementById(this.id).removeAttribute("style");
            document.getElementById(this.id).setAttribute("class", "free");
        } else {
            document.getElementById(this.id).removeAttribute("style");
            document.getElementById(this.id).setAttribute("class", "occupied");
        }
    });
}

密码笔

我不知道如何在 Angular 中实现它,或者如何让它更简单。当然还有如何选择最多 9 个座位。

我将不胜感激您的任何建议和帮助。

堆栈闪电战

标签: javascriptcssangulartypescript

解决方案


您可以将 onClick 功能添加到 path=seats

<g id="seats"  (click)="onClick($event)">

然后使用closest方法获取座位,它被点击了。在您的示例中,所有座位路径都有 class st121。这意味着我们可以坐下来$event.target.closest('.st121');

对于最大座位,您可以添加一个柜台并注意它。

import {
    Component,
    OnInit
} from '@angular/core';

const MAX_SEATS = 9;
@Component({
    selector: 'app-seatmap',
    templateUrl: './seatmap.component.html',
    styleUrls: ['./seatmap.component.css']
})
export class SeatmapComponent implements OnInit {
    constructor() {}
    ngOnInit() {}

    counter = 0;

    onClick($event) {
        const seat = $event.target.closest('.st121');
        if (!seat) {
            return;
        }

        const res = seat.getAttribute("class").split(' ').indexOf('occupied');

        if (res > -1) {
            seat.removeAttribute("style");
            seat.setAttribute("class", "free st121");
            this.counter -= 1;
        } else if (this.counter < MAX_SEATS) {
            seat.removeAttribute("style");
            seat.setAttribute("class", "occupied st121");
            this.counter += 1;
        }


    }

}


推荐阅读