首页 > 解决方案 > 刷新组件后突出显示选定的列表项

问题描述

场景:我有一个名为 的组件,它在列表list中显示所有内容。customers在这个列表中,我写了这样的条件:

1) 默认情况下 1stlist-item(Ex customer 1)将被选中,并且选中的list-item(Ex customer 1)将被发送到另一个名为display.

2)然后单击任何 list-item(i,e customer)选定的列表项也发出display组件。如下图所示:

在此处输入图像描述 在此处输入图像描述

联系人列表组件代码:

HTML

<mat-selection-list>
    <mat-list-option [ngClass]="{selected : currentContact && contact.Name == currentContact.Name}" *ngFor="let contact of contacts">
           <a mat-list-item (click)="onSelect(contact)">{{ contact.Name }} </a>
    </mat-list-option>
</mat-selection-list>

CSS

.selected {
  background-color:gray;
}

TS

import { Component Input,EventEmitter,Output} from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';

@Component({
  selector: 'drt-customers-list',
  templateUrl: './customers-list.component.html',
  styleUrls: ['./customers-list.component.scss'],
})
export class CustomerListComponent {
 public customers:  ICustomer[] ;
   public currentContact: IContact;
 @Output()
 public select = new EventEmitter();

 constructor(public customersService: CustomersService,) {}

  public async ngOnInit(): Promise<void> {
    this.customers = await this.customersService.getCustomersList('');
    this.customerRefreshed();
  }

   public ngOnChanges(changes: SimpleChanges): void {===>To emit 1st contact by default
    if (this.contacts && this.contacts.length > 0) {
    this.currentContact = this.contacts[0];
    this.select.emit(this.currentContact);
    }
   }

  public customerRefreshed() { ====> To refresh the list after updating
    this.customersService.customerUpdated.subscribe((data: boolean) => {
        if(data) {
            this.customers = await this.customersService.getCustomersList('');
        }
    });  

  }

  public onSelect(contact: IContact): void {===> To emit contact on click
    this.select.emit(contact);
  }


}

现在我有另一个组件update the contacts,我将contact通过执行PUT操作更新选择然后我将再次刷新contact-list。查看更改。

update-contact 组件代码:

public updateCustomer(): void {
    this.someCustomer = this.updateForm.value;
    this.customersService.UpdateCustomer(this.someCustomer, this.someCustomer.id).subscribe(
      () => {  // If POST is success
        this.customersService.customerUpdated.next(true);
        this.successMessage();
      },
      (error) => {  // If POST is failed
        this.failureMessage();
      }
    );
  }

服务文件:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})

export class CustomersService {
 private  baseUrl : string = '....Url....';
 public  customerUpdated: Subject<boolean>;


  constructor() {
    this.customerUpdated = new Subject<boolean>();
 }

  public async getCustomersList(): Promise<ICustomer[]> {
    const apiUrl: string = `${this.baseUrl}/customers`;
    return this.http.get<ICustomer[]>(apiUrl).toPromise();
 }

  public UpdateCustomer(customer: ICustomer, id: string): Observable<object> {
     const apiUrl: string = `${this.baseUrl}/customers/${id}`;
     return this.http.post(apiUrl, customer);
  }

}

现在的问题,假设如果我select/click是第二次list-item(Customer 2) 更新,那么在更新后list-item(Customer 1)默认选择如下:

在此处输入图像描述

但是在更新之后,之前点击的list-item(Customer 2)必须selected再次处于状态,即使在刷新之后也是list这样在此处输入图像描述

标签: angulartypescriptangular6

解决方案


出现此行为是因为您currentContact在更新联系人时始终在此方法中重置:

public ngOnChanges(changes: SimpleChanges): void {
    if (this.contacts && this.contacts.length > 0) {
        this.currentContact = this.contacts[0];
        this.select.emit(this.currentContact);
    }
}

尝试这样的事情:

public ngOnChanges(changes: SimpleChanges): void {
    if (this.contacts && this.contacts.length > 0) {
        const fallback = this.contacts[0];
        if (this.currentContact) { // Check if it was set before
            // Check if the contact is still present
            const stillThere = this.contacts.find(contact => contact.id === this.currentContact.id);
            this.currentContact = stillThere ? stillThere : fallback;
        } else
            this.currentContact = fallback;
        this.select.emit(this.currentContact);
    }
}

推荐阅读