我有一个名为contact-list
的组件。此组件用于显示带有照片的联系人列表,如下所示:
background -color
和text-color
已更改)。 display
的组件在右侧显示此所选联系人的详细信息,这里是contact-list
组件代码:
HTML
<mat-selection-list>
<mat-list-option [ngClass]="{selected : contact.fullName == currentContact.fullName}" *ngFor="let contact of contacts">
<a mat-list-item (click)="onSelect(contact)"><img src="{{contact?.pictureUrl}}" > <span>{{ contact?.fullName }}</span> </a>
</mat-list-option>
</mat-selection-list>
TS
import {Component, EventEmitter, Input , Output, ViewChild } from
'@angular/core';
import { IContact } from 'src/app/models/app.models';
@Component({
selector: 'btn-contact-list',
templateUrl: './contact-list.component.html',
styleUrls: ['./contact-list.component.scss'],
})
export class ContactListComponent {
@Input()
public contacts: IContact[] ;
@Output() public select: EventEmitter<{}> = new EventEmitter();
public currentContact: IContact;
public ngOnInit(): void {
if (this.contacts && this.contacts.length > 0) {
this.currentContact = this.contacts[0];
this.select.emit(this.currentContact);
}
}
public onSelect(contact: IContact): void {
this.currentContact = contact;
this.select.emit(contact);
}
}
答案 0 :(得分:1)
在访问undefined
的属性之前,应该对对象object
进行附加检查。您可以按以下方式修改代码-
<mat-list-option
[ngClass]="{selected : contact && currentContact && contact.fullName == currentContact.fullName}"
*ngFor="let contact of contacts">