我有2个组成部分:1)contact
2)display
。
contact
组件用于显示联系人列表,如下图所示:
另一个组件“显示”,我将其放置在contact
组件的右侧,如下所示:
现在列表中changing/clicking
个联系人(即联系人组件中的联系人)上。我正在右侧组件(即display
组件)上显示特定的联系人数据(即电子邮件,性别...),如第二幅图像所示。
现在的问题是:
联系人组件代码
HTML
<mat-selection-list>
<mat-list-option [ngClass]="{selected : currentContact && 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>
SCSS
.selected {
background-color:blue;
}
.selected span{
color:red;
}
TS
import {Component ,EventEmitter ,Input ,Output, ViewChildfrom
'@angular/core';
import { IContact } from 'src/app/models/app.models';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.scss'],
})
export class ContactComponent {
@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);
}
}
显示组件代码
HTML
<div>
<tr>
<td>Email </td>
<td>{{contact?.eMailAddresses}} </td>
</tr>
<tr>
<td>Gender</td>
<td>{{contact?.gender}} </td>
</tr>
</div>
TS
import {Component, EventEmitter, Input , Output, ViewChild} from
'@angular/core';
import { IContact } from 'src/app/models/app.models';
@Component({
selector: 'app-display',
templateUrl: './display.component.html',
styleUrls: ['./display.component.scss'],
})
export class DisplayComponent {
@Input()
public contact: IContact;
}
Stackblitz DEMO
答案 0 :(得分:2)
尝试添加ngOnChanges
来跟踪尚未加载的ngInint contacts
上的联系人。
代码:
import { Component, Input, Output, EventEmitter, SimpleChanges, OnInit, ViewChild } from '@angular/core';
ngOnChanges(changes: SimpleChanges) {
if (this.contacts && this.contacts.length > 0) {
this.currentContact = this.contacts[0];
this.select.emit(this.currentContact);
}
}