In Angular, set the default value of the first item in the list to be highlighted when the page loads

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

Answer №1

Consider implementing ngOnChanges to monitor changes in contacts when ngInit is called and contacts are not yet loaded.

Example:

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); 
    } 
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the contrast between Angular 2 components and directives?

I have been having difficulty grasping the distinction between these two ideas within the framework. I am quite experienced with directives in AngularJS 1.x, and both components and directives in Angular 2 appear to be closely related to this concept... ...

Adding Custom CSS File to an iFrame in Angular

Currently, I am attempting to include a CSS file in a third-party iframe to modify its styling. My initial idea was to employ the following code snippet: ngOnInit() { ... this.myIframe.nativeElement.document.head.appendChild('style.css') } U ...

Issue with Angular 4 Routing: Links are opening in new window instead of within router-outlet

I am currently facing an issue while trying to display the SuburbDataComponent HTML on the DASHBOARD-SIDE-PANEL-COMPONENT.HTML. When I click on Dashboard, it opens a new window but only displays the SuburbDataComponent.html without showing the side panel ...

Jest.useFakeTimers() causing clearTimeout test to malfunction

I've been exploring the transition to the newer version of jest.useFakeTimers(), which is not set as default in the latest 27.x release. Encountering some issues during my tests, Jest keeps flagging that functions like clearTimeout and setInterval a ...

Is there a way to insert a Highchart Image into a spreadsheet in Excel?

Struggling to insert a Highchart's chart image into an Excel file? The goal is to utilize the current "Export Excel" button on a website to export a static image of the Highchart displayed on the webpage directly into an excel spreadsheet. Provided be ...

Issue encountered when trying to integrate Angular2 with Visual Studio 2015 Update

Starting my journey with Angular2 in Visual Studio 2015. Following advice from this helpful article. Encountering an issue when running the index.html file, it gets stuck on 'Loading...'. Here are the key configurations and code files being use ...

Union does not contain the specified property in Typescript

Here are the types that I have: Foo { foobar: any } Bar { fooBarBar: any; } I want to use a function defined like this: this.api.submit(param: Foo | Bar) When trying to use it, I encountered an issue: this.api.submit(param.foobar) // does no ...

Step-by-step guide on invoking an asynchronous method in canActivate for Ionic and Angular

My objective is to acquire a token for authenticating users. I am utilizing the import { Storage } from '@ionic/storage-angular'; to store the data, but I am encountering an issue where the Storage methods only function in asynchronous mode. Her ...

Encountered an error while attempting to execute Angular application due to schema validation failure

Encountering errors in my Angular 7 Application on the development server. After running ng serve, below is the error that surfaced: D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1>ng lint -fix Your global Angular CLI ...

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...

Tips for identifying two mat-tables within the same component in Angular UI

Having trouble with rendering rows in two mat-tables within the same component. The renderRows() function is not working for the second table. @ViewChild(MatTable) tagsTable: any; @ViewChild(MatTable) serviceAreaTable:any; this.tagsTable.renderRows(); # ...

Error: Unable to use import statement outside of a module when deploying Firebase with TypeScript

Every time I try to run firebase deploy, an error pops up while parsing my function triggers. It specifically points to this line of code: import * as functions from 'firebase-functions'; at the beginning of my file. This is a new problem for me ...

Convert an interface type variable to a string representation

I'm just starting to learn angular and I'm attempting to convert my response from an interface type into a string so that I can store it in session storage. However, when I try to save them, they are being stored as [object] in the session storag ...

There was a TypeScript error found at line 313, character 9 in the file @mui/material/styles/experimental_extendTheme.d

Encountering Typescript error while using Material UI component for date range picker Link - https://mui.com/x/react-date-pickers/date-range-picker/ Snippet of the code import * as React from 'react'; import { Dayjs } from 'dayjs'; im ...

Repetitive cycling through an array

My array consists of classes: const transferClasses = [ { id: "c5d91430-aaab-ed11-8daf-85953743f5cc", name: "Class1", isTransfer: false, children: [], }, { id: "775cb75d-aaab-ed11-8daf-85953743f5cc", ...

Utilizing Typescript to inject dependencies and receive arguments within a class

I am currently using InversifyJS with the container. My goal is to inject the templateEngine and provide args (such as host, port, etc...) in the constructor. const container = new Container(); container.bind<MailerInterface>(TYPES.Mailer).to(NodeM ...

What security measures does Angular implement to safeguard against malicious user input?

While I was learning how to build a router in vanilla JS, the tutorial author mentioned that it's advisable to use frameworks like Angular or React for various reasons. The author pointed out that Angular, for example, sanitizes user input before inse ...

The file isn't located in 'rootDir', even though all the details seem to be accurate

I'm currently troubleshooting an issue with one package in my nx monorepo that is causing the error code "TS6059". Interestingly, all other packages are functioning correctly in previous builds. After reviewing my index.ts files, it appears that all ...

Challenge with React CloneElement regarding typing

Utilizing React Children and React Clone element, I aim to trigger methods in both the wrapper and Select components upon onClick event in the Option component. Although everything is functioning correctly, I am encountering a type error when calling the O ...

How to create a beautiful grid layout using @angular/flex-layout, @angular/material, and mat-card to showcase stunning images

I have created a basic layout that looks like this: Cell 0 Cell 1 Cell 2 <!-- these are not to appear in actual render __________________________________ | Image 0 | Image 1 | Image 2 | |----------| Image 1 |----------- | text here| ...