因此,我试图使用Angular创建一个网站,并且遇到了一个非常特殊的错误。基本上我有一个* ngFor div,它创建12个按钮。
<div *ngFor = "let color of colors; let i = index" style = "display: inline;">
<button (click) = "toggleTrue(i)" id = "{{i}}" class = "coloredButton">
</button>
</div>
单击按钮后,它应突出显示该按钮,然后像这样在我的组件中更改数组中的值。
toggleTrue(id: number){
this.colors[id] = !this.colors[id];
var button = document.getElementById(id.toString());
if(this.colors[id] === true){
button.style.border = "10px";
button.style.borderColor = "white";
button.style.borderStyle = "solid";
}
else{
button.style.borderStyle = "none";
}
}
但是由于某种原因,每当我单击一个按钮时,它都会高亮显示其旁边的按钮;如果单击两次超过两次,则由于某种原因,它将高亮显示一个按钮两个按钮,请再次单击两次,它将高亮显示一个按钮三个按钮等等。它没有突出显示右键,但是它传递给函数的id是正确的,我使用console.log(id)进行了检查。
我已经弄乱了一些(取出类,行和其他内容),并且将问题隔离到此行。
this.colors[id] = !this.colors[id];
如果我删除了它,那么一切工作正常(当然,我不能再编辑数组的值了)。当我删除按钮的单击功能并且按钮的默认突出显示正确突出显示右侧按钮时,这一点得到了进一步证明。谁能帮我一下,告诉我为什么突出显示不正确?任何帮助,将不胜感激。如果您很好奇,我会在组件中使用colors = []创建数组,这是我使用基本的for循环在构造函数中填充的布尔数组。
https://codesandbox.io/s/crimson-brook-wn3q0?file=/src/app/app.component.html
这是带有解决方案的沙箱。本质上,您希望通过使用NgClass或NgStyle来保持模板样式,并仅将组件用于更改状态,避免由于生命周期问题而直接访问DOM。
打字稿
export class AppComponent {
colors: boolean[];
constructor() {
this.colors = [];
for (let i = 0; i < 10; i++) {
this.colors.push(false);
}
}
toggleTrue(id: number) {
this.colors[id] = !this.colors[id];
}
}
的HTML
<div>
<div *ngFor="let color of colors; index as i">
<button
(click)="toggleTrue($event, i)"
id="{{i}}"
[ngClass]="{'active':colors[i]==true}"
>
button
</button>
</div>
</div>
的CSS
.active {
color: red;
}
.inactive {
color: blue;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句