【问题标题】:To highlight the selected list-item after refreshing the component刷新组件后突出显示选定的列表项
【发布时间】:2019-08-25 23:31:08
【问题描述】:

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

1) 默认情况下,第一个 list-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,我将通过执行PUT 操作更新选定的contact,然后我将再次刷新contact-list。查看更改。

更新联系人组件代码:

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之后

【问题讨论】:

    标签: angular typescript angular6


    【解决方案1】:

    出现这种行为是因为当您的联系人更新时,您总是在此方法中重置 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);
        }
    }
    

    【讨论】:

    • 感谢您的解决方案。
    猜你喜欢
    • 2019-08-22
    • 2012-02-02
    • 1970-01-01
    • 2013-12-22
    • 2014-11-28
    • 2013-10-26
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多