In my project, there are two key components: 1)contact
and 2)display
.
The contact
component is responsible for displaying a list of contacts as shown in the image below:
https://i.sstatic.net/SnXFZ.png
Next to the contact
component, I have placed another component called 'display' which looks like this:
https://i.sstatic.net/jkebb.png
When a user changes or clicks on a contact from the list (in the contact component), the details of that specific contact such as email, gender, etc., are displayed on the right side component (the display component) just like in the 2nd image.
However, here is the issue I am facing:
- I need the first contact to be highlighted by default.
- Also, the data of the first highlighted contact (email, gender, etc.) should be displayed on the right side (in the display component) similar to the 2nd image.
Contact Component Code
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, ViewChild} from
'@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);
}
}
Display Component Code
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;
}
Check out the Stackblitz DEMO