我正试图找到用Blazor点击事件打开和关闭css类的最佳方法。此功能包括单击由@foreach生成的列表框列,只更改活动框的样式,然后在随后单击其他框时禁用它。简而言之,只有活动框在单击时更改样式,而所有其他框都没有更改样式。
我从下面的代码开始,它正确地创建了框,但它将"活动"应用于所有列表框,而不仅仅应用于当前活动的框(这仍然在POC中,因此一些代码仍然需要重构(:
@foreach (var msg in Message)
{
<a class="list-group-item list-group-item-action @(ActiveClass ? "active" : "")" data-toggle="list" href="#home" role="tab" @onclick="() => popIt(msg.MsgId)">
<span id="msgSubject1">@msg.Subject</span><br /><span class="datetimeCls" id="datetime1">@msg.DateCreated</span>
</a>
}
private bool ActiveClass { get; set; }
public void popIt(int num)
{
var text = Message[num].MessageText;
var subject = Message[num].Subject;
Subject = subject;
MessageText = text;
DateCreated = Message[num].DateCreated;
ActiveClass = true;
}
Angular 8有内置的"ngClass"。下面的代码适用于这个场景——Blazor有类似的东西吗?我还注意到Angular点击可以处理两个输入,这是我在Blazor中还没有看到的:
<div *ngFor="let msg of messages; let i = index" >
<a class="list-group-item list-group-item-action" data-toggle="list" href="#home" role="tab" [ngClass]="{ 'active' : msg == activeMessage}"(click)="activeMessage = msg;popIt(i)">
<span id="msgSubject1">{{msg.Subject}}</span><br /><span class="datetimeCls" id="datetime1">{{msg.DateCreated | date : 'short' }}</span>
</a>
</div>
</div>
下面的代码似乎可以工作。它创建一个名为"ActiveMessageId"的新变量,并将单击的消息id分配给该消息。
@foreach (var msg in Message)
{
<a class="list-group-item list-group-item-action @(ActiveMessageId == msg.MsgId ? "active" : "")" data-toggle="list" href="#home" role="tab" @onclick="() => popIt(msg.MsgId)">
<span id="msgSubject1">@msg.Subject</span><br /><span class="datetimeCls" id="datetime1">@msg.DateCreated</span>
</a>
}
private int ActiveMessageId { get; set; }
public void popIt(int num)
{
var text = Message[num].MessageText;
var subject = Message[num].Subject;
Subject = subject;
MessageText = text;
DateCreated = Message[num].DateCreated;
ActiveMessageId = num;
}