gpt4 book ai didi

Angular 2 - 选择单击的列表项(添加 'active' 类并从 sibling 中删除)

转载 作者:太空狗 更新时间:2023-10-29 16:55:44 24 4
gpt4 key购买 nike

我在下面的代码片段中有如下列表项。单击鼠标我想选择该项目(添加“事件”类并取消选择是否有任何其他项目( sibling )被删除“事件类”选择。我已经使用 jQuery(下面的完整代码)实现了相同的目标。我如何实现Angular 2 方式的功能。

代码片段:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<ul id="grouplist" class="list-group">
<li class="list-group-item">Item1</li>
<li class="list-group-item">Item2</li>
<li class="list-group-item">Item3</li>
<li class="list-group-item">Item4</li>
<li class="list-group-item">Item5</li>
<li class="list-group-item">Item6</li>
<li class="list-group-item">Item7</li>
<li class="list-group-item">Item8</li>
<li class="list-group-item">Item9</li>
<li class="list-group-item">Item10</li>
</ul>
<script>
$(function () {
$('.list-group li').click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
})
</script>
</body>
</html>

JSFiddle here

Angular 2 实验:我可以通过“setElementClass”设置类。如何从 sibling 中删除“活跃”类(class)?或者还有其他方法吗?

ListView 组件(test1.component.html):

<h2>Select List Item</h2>

<ul id="grouplist" class="list-group">
<li class="list-group-item" (click)="listClick($event)" *ngFor="let item of groups">
{{ item.name }}
</li>
</ul>

TypeScript 代码(test1.component.ts):

import { Component } from '@angular/core';
import { Renderer } from '@angular/core';
import { Group } from './group';

@Component({
selector: 'test1',
template: require('./test1.component.html')
})
export class Test1Component {

groups: Group[];

constructor(private render: Renderer) {
this.groups = [new Group("item1"), new Group("item2"), new Group("item3"), new Group("item4"), new Group("item5")];
}

public listClick(event: any) {
event.preventDefault();
this.render.setElementClass(event.target, "active", true);
// How to remove 'active' from siblings ?
}
}

组.ts

export class Group {
constructor(public name: String) {
}
}

最佳答案

您可以将 ngClass 用于您要查找的内容:

 <ul id="grouplist" class="list-group">
<li class="list-group-item" [ngClass]="{'active': selectedItem == item}" (click)="listClick($event, item)" *ngFor="let item of groups">
{{ item.name }}
</li>
</ul>

然后在您的 listClick 中将所选项目设置为该项目:

listClick(event, newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}

关于Angular 2 - 选择单击的列表项(添加 'active' 类并从 sibling 中删除),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40986464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com