【问题标题】:Class is not added to the first div that is dynamically added类不添加到第一个动态添加的div
【发布时间】:2018-04-18 02:03:10
【问题描述】:

在我的 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
 }

我该怎么做?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以尝试使用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});
     }
    

    【讨论】:

    • @aeshnaKashyap .. 我已经编辑了我的答案以使用 NgClass 指令。希望这对你有用。
    猜你喜欢
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    相关资源
    最近更新 更多