Filtering Data in Angular by ID

I am looking to utilize some data within an angular project instead of relying on a database due to its small size, consisting of about 50 id's with 5 fields. Here is the sample data:

mydata = [

  {
    "id": 3,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 3"
  },
  {
    "id": 31,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 31"
  },
  {
    "id": 11,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text for 11"
  },
  {
    "id": 21,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 21"
  }

]

Next, I have designed a method as follows:

getDataText(id) {
    // code implementation to fetch the text based on the selected id
    // this should provide me with the data (specifically the text for id 11) 
}

In my component.html file, I have included this snippet:

<button (click)="getDataText(11)">Get Data by Id</button>

How can I achieve this functionality?

Answer №1

Give this a shot:

fetchDataById(id) {
    let dataFound = this.myData.find(item => item.id === id);
    if (typeof dataFound === 'undefined') {
       return null;
    }
    return dataFound;
} 

Keep in mind, if no match is found based on the condition, the result will be undefined.

Answer №2

It is essential for this to be functional:

retrieveData(id) {
    const outcome = this.customdata.filter(y => y.id === id);
    return outcome;
}

Answer №3

Make sure your getDataText function is structured like this:

getDataText(id) {
  const data = myData.find(x => x.id === id);
  return data ? data.text : `No data found with id ${id}`;
}

If you prefer, you can break it into two separate functions:

getDataById(id) {
  return myData.find(x => x.id === id);
}

getDataText(id) {
  const data = this.getDataById(id);
  return data ? data.text : `Cannot locate data with id ${id}`;
}

Answer №4

fetchDataText = identifier => (this.dataSet.find(item => item.identifier === identifier) || {}).text;

This function retrieves the text of the element identified by the given identifier, returning undefined if no such element exists.

Answer №5

let message = "Retrieving Data using ID";
function retrieveData(id) {
  const requestData = this.mydata.find(item => item.id === id);
  this.result = requestData ? requestData.text : 'no data found';
}


<button (click)="retrieveData(11)">{{result}}</button>

Check out my sample

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

Angular2 encountering a lack of service provider issue

After finding the code snippet from a question on Stack Overflow titled Angular2 access global service without including it in every constructor, I have made some modifications to it: @Injectable() export class ApiService { constructor(public http: Http ...

Type information is lost when toString() is returned after traveling through HttpClient on Angular 10

I created a Foobar class with a custom toString() method that works perfectly fine in most cases, except when the Foobar object is returned from a REST call. The following code snippet and its output demonstrate this issue: FOOBAR-1 behaves as expected, wh ...

"When attempting to render a Node inside the render() method in React, the error message 'Objects are not valid as a React child' is

On my webpage, I have managed to display the following: export class OverworldComponent extends React.Component<OverworldComponentProps, {}> { render() { return <b>Hello, world!</b> } } However, instead of showing Hello, ...

Determining the ideal timing to log timestamps from the user interface is crucial

When integrating an API to log errors and monitor metrics from the UI, is it ideal to obtain the timestamp directly from the UI during the event or should the timestamp be added when the log request reaches the API? ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

Learn how to dynamically adjust context using a server-client architecture with TRPC

Currently, I am referring to the tRPC documentation for guidance on creating a server side caller. But I'm facing a challenge in dynamically setting the value when incorporating it into my NextJS 13 pages. In my context.ts file, you will find the fol ...

Error is being thrown due to defining a variable after it has already been declared and

Before I use a variable, I encountered the issue of using it before its definition, interface IProps extends WithStyles<typeof STYLES>; const STYLES = () => ({ }) Although it didn't cause any errors, a warning appeared: STYLES used befo ...

From HTML element to pug-template with the use of the # symbol

I have a code snippet with 2 angular material radio buttons. Both of them contain the #attribute/element (I'm not sure what it's called) within them. How can I convert them into pug so that the attribute/element with the # works? Below is the sam ...

Rollup plugin for TypeScript fails to transpile Babel 7 code

I've been encountering issues trying to use rollup-plugin-babel in my typescript project. Despite the .ts code compiling and rollup generating map files, babel does not seem to transpile it. Interestingly, when I execute npx babel lab.js --out-file l ...

Is it possible to utilize both $uibModal and $uibModalInstance within the same controller to create a modal popup in an Angular project incorporating TypeScript?

Being new to Angular with Typescript, I encountered an issue while trying to implement a modal popup in Angular. The problem arises when I have a dropdown menu that triggers the opening of a modal popup with two buttons, "Yes" and "No". To handle this, I h ...

To ensure that the spied function is not called, be sure to use Jest's spyOn function

As per my notes from Jest: Note: By default, jest.spyOn also triggers the spied method. Within my Angular component. ngAfterViewInit(): void { this.offsetPopoverPosition(); } In my spec: it('Expect ngAfterViewInit() to call offsetPopoverPosition ...

Performing unit tests in Angular 2 with karma

Trying to grasp the concept of unit testing in Angular has been quite a challenge for me, especially since I am still navigating through Angular 2 and its syntax. Understanding testing becomes even more intricate. I attempt to follow the examples provided ...

Is ConnectionServiceModule not compatible with Angular version 17.2.0?

I have encountered an issue in my Angular project that involves the compatibility of the ng-connection-service library with Angular Ivy. When I attempt to bring in the ConnectionServiceModule from the ng-connection-service into my Angular module, I am rece ...

The ng-if element briefly appears before vanishing from sight

In my HTML code, I have the following: <ul class="navbar-nav" > <li><a *ngIf="isLoggedIn" routerLink="/welcome/in28minutes" class="nav-link">Home</a></li> <li><a *ngIf="isLoggedIn" routerLink=" ...

What could be causing the lack of functionality when defining a CSS role using :host ::ng-deep within an Angular component's stylesheet?

My knowledge of Angular and CSS is limited, and I am facing a problem when trying to define a CSS style for a specific component in the .css file. If I use the following code snippet: .p-column-title { display: none; } it works perfectly. However, wh ...

The 'prop' property is not found within the 'IntrinsicAttributes & CustomComponentProps' type

I developed a custom module with an interface for props, extending props from a file called /types/SharedProps.d.ts. However, when I import this module into a sample project, the extended props are not included in the component. Below is how the module&apo ...

Unable to allocate submit event category

This is a question about code and an error message. The code snippet is shown below: const handleSubmit = (e: React.FormEventHandler<HTMLFormElement>) => { // e.preventDefault() } <form onSubmit={handleSubmit}></form> Below is ...

Angular 2 - Post-Constructor Lifecycle Event Triggered

I am currently working on a project using Angular 2. After calling the component's constructor, I need to capture an event that indicates when the constructor call has completed. In my constructor, I am making a network call like this: import { Comp ...

The functionality of @Output and custom events appears to be malfunctioning

I am a beginner in Angular and attempting to pass data between child and parent components. In the child component.ts file: @Output() doubleClick = new EventEmitter<string>(); onDoubleClick(nameAccount: string){ this.doubleClick.emit(nameAccoun ...

Show variously colored information for each selection from the dropdown using Angular Material

I am trying to change the color of displayed content based on user selection in an Angular application. Specifically, when a user chooses an option from a dropdown list, I want the displayed text to reflect their choice by changing colors. For example, i ...