类未添加到动态添加的第一个div中

时间:2018-04-17 17:18:30

标签: angular

在onInit函数的角度应用中,我正在获取一些值并以这种方式显示它 user.component.ts

 ngOnInit() {
  this.method={method:"fetchTickets",user:ntid,ticketId:"12332"}
  this.subscription1= this.userService.getTickets(this.method).subscribe(ticket =>{
  this.tickets=ticket.data;
})

user.component.html

  <div class="Users" id="foo">
  <div class="ruser mb-2" #tickets  *ngFor="let ticket of tickets" (click)="fetchMsg(ticket)">
    <div class="rname z-depth-2 hoverable {{ticket.id}}">
      <h5>{{ticket.id}}</h5>
    </div>
  </div>
  </div>

所以现在在按钮上单击我将数据添加到门票数组的开头,该数组将自动显示在用户div中,但是当我向第一个元素添加一个类,即按钮点击后添加的一个类时,该类是被应用于第二个.rname div

fetcMsg(ticket)
{
  this.tickets.unshift({id:this.ticketRand,resolved:true,time:d});
  $('.rname:first').addClass('selected'); //this applies to the second rname 
  div
  $('.'+this.ticketRand).addClass('selected'); //this does not apply at all
 }

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用NgClass指令。

<div class="Users" id="foo">
      <div class="ruser mb-2" #tickets  *ngFor="let ticket of tickets" (click)="fetchMsg(ticket)">
        <div [ngClass]="{'selected': ticket.id == ticketRand}" class="rname z-depth-2 hoverable {{ticket.id}}">
          <h5>{{ticket.id}}</h5>
        </div>
      </div>
</div>

fetchMsg方法如下所示:

fetchMsg(ticket){
  this.tickets.unshift({id:this.ticketRand,resolved:true,time:d});
 }