How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-workers-edit',
  templateUrl: './workers-edit.component.html',
  styleUrls: ['./workers-edit.component.css']
})
export class WorkersEditComponent implements OnInit {
  public workerid;
  public lastname;
  public address;
  public phone;
  public email;

  workers = [];

  constructor(private route: ActivatedRoute, private http: HttpClient) { }

  ngOnInit() {
    let id = parseInt(this.route.snapshot.paramMap.get('id'));
    this.workerid = id;

    let Workerobs = this.http.get('http://myurlPP/cfcs/workernameapi.cfm');
    Workerobs.subscribe((res:any)=> {
      console.log(res);
      this.workers = res;

    });

  }

}

The array 'workers' now contains all the information coming from the server: https://i.sstatic.net/BKX4E.png

In my HTML file, I am currently looping through all the names in the 'workers' array like this:

<ul>
    <li *ngFor="let name of workers">{{name.WNAME}}</li>
</ul>

However, I need to only display the name that matches the 'workerid' value. This is stored in this.workerid after extracting it from the URL parameter.

How can I filter out the correct object from the 'workers' array based on 'workerid' and display only the corresponding 'WNAME' (worker name)?

Answer №1

Filtering your array can be done directly within the subscribe function

Workerobs.subscribe((res:any)=> {
    console.log(res);
    this.workers = res.filter(item => item.WID === this.workerid);
});

It's important to double-check property names used in the filter function to ensure they match your specific case.

Answer №2

onInit() {
    let identity = parseInt(this.route.snapshot.paramMap.get('identity'));
    this.workIdentify = identity;

    let WorkerObs = this.http.get('http://myUniqueURL/cfcs/workerapi.cfm');
    WorkerObs.subscribe((response:any)=> {
      console.log(response);
      this.workerRecords = response.filter((person) => person.id === this.workIdentify);
    });

  }

All that is required is to perform the filter operation on the worker data array as demonstrated above.

Answer №3

If you follow the code below, you will be able to achieve the desired functionality:

<ul>
    <li *ngFor="let name of workers">
        <ng-container *ngIf="name.WID == this.workerid">{{name.WNAME}}</ng-container>
    </li>
</ul>

Implementing this should help you accomplish what you need. Feel free to ask if you require any modifications in functionality.

Answer №4

If you want to achieve a clean display in your user interface, simply include the conditional statement *ngIf="condition":

<ul>
   <li *ngIf="worker.WID == workerid" *ngFor="let worker of workers">{{worker.WNAME}}</li>
</ul>

Answer №5

If the Worker ID is guaranteed to be unique, it is recommended to utilize the find method instead of filter. This way, you can retrieve the first matching item in the array.

selectedWorker: any;

constructor(private route: ActivatedRoute, private http: HttpClient) { }

ngOnInit() {
  let id = parseInt(this.route.snapshot.paramMap.get('id'));
  this.workerid = id;

  let Workerobs = this.http.get('http://myurlPP/cfcs/workernameapi.cfm');
  Workerobs.subscribe((res:any)=> {
    this.selectedWorker = res.find((worker) => worker.workerid === this.workerid);
    if (this.selectedWorker === undefined) {
       console.log('No worker with an id of ' + id + ' was found.');
    }
  });

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

Techniques for triggering JavaScript on elements that have been dynamically loaded via Ajax

When it comes to ensuring that a certain functionality works both when the document is ready and after an Ajax call, there are some considerations to keep in mind for optimal performance. An approach I found effective involves defining the desired code wi ...

Access a document from a collaborative directory directly in a web browser

When I paste the shared path for a PDF file into the address bar, it opens perfectly in all browsers. The code below works fine in IE 8 but not in Chrome and Firefox. Code: function openPDF(file) { window.open(file, '_blank'); } function link ...

Implementing a dynamic module or dependency addition using a webpack plugin: A comprehensive guide

I'm feeling a bit frustrated because what I am trying to accomplish doesn't seem too difficult, but the documentation for webpack is so disorganized that it's eating up a lot of my time. Can someone please explain how I can inject a "dynami ...

Utilizing jquery to showcase the information in a neat and organized table

Having an input text box and a button, I am looking to display dummy data in a table when any number is entered into the input field and the button is clicked. Here is what I have tried: My Approach $("button#submitid").click(function () { $(&quo ...

What could be the reason that my Bootstrap design is displaying narrower than the designated container?

Having some issues with a JavaScript code that involves innerHTML, causing a discrepancy in width compared to the CSS and Bootstrap rules I have set up. Below is the JavaScript code snippet: let numeroStreams = document.getElementById('num') let ...

Require field change in SharePoint 2010

I have implemented the following code on a SharePoint page - it locates the specified select based on its title and triggers an alert when the "Decision" value is selected. I am interested in removing the alert and instead substituting with code that iden ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

Exploring the benefits of integrating Apache Thrift with TypeScript

After running the apache thrift compiler, I now have generated .js and .d.ts files. How do I incorporate these files into my current Angular2/Typescript project? I attempted to do so with the following lines of code: ///<reference path="./thrift.d.ts"/ ...

Tips for saving/downloading generated QR codes in React Native

Using this code allows me to generate QR Codes, but I am struggling with saving the generated QR Code in PNG or JPEG format. I have tried a few examples without success and I am continuing to try different methods. import React, { Component } from 'r ...

Display validation errors in Angular2 forms when the form items are left empty and the user tries to submit the form

In my application, I have a userForm group containing keys such as name, email, and phone. Additionally, there is an onValueChanged function that subscribes to changes in the form and validates the data. buildForm(): void { this.userForm = this.fb.gr ...

Utilizing reference memory to enable communication between two controllers

Within my Angular application, I have implemented a service to facilitate communication between 2 controllers and allow them to share the input variable from the search box. I am using kickSearch.box to reference memory...obj.property. However, there seem ...

Vue 3 app encountering error due to element having an 'any' type implicitly

I want to incorporate lucidev icons into my component, but I am fairly new to typescript. You can find the lucidev icons here: https://github.com/lucide-icons/lucide <template> <component :is="icon" /> </template> <script ...

Issue encountered while attempting to send a direct message to a user that has been mentioned

Attempting to create a reminder command in discord.js with two arguments: the message and the mentioned user to remind but encountering an error. Code snippet: client.on('message', (message) => { const { content, guild, channel, author } = m ...

Leveraging both the spread operator and optional fields can improve the productivity and readability of your

Imagine you have an object with a mandatory field that cannot be null: interface MyTypeMandatory { value: number; } Now, you want to update this object using fields from another object, but this time with an optional field: interface MyTypeOptional ...

Unable to insert a JSON object into an array using JavaScript and MongoDB

I'm encountering an issue when trying to push data into my Student model with the following schema: var StudentSchema = new Schema({ firstName: { type: String, trim: true, default: '' //validate: [validat ...

Exploring Angular 4: Leveraging mockRespond in Conjunction with RxJS Observables

I recently completed the development of an application that is functioning smoothly. Now, I am in the process of creating a test for it. The core functionality involves fetching items from an API backend: export class CatfactService { constructor(p ...

Is it possible to dynamically add the URL to an iframe based on a condition being true, and then iterate through a list of URLs before

I'm trying to figure out how to change the URL in an iframe based on the presence of a class="show". The first time the element has the class "show," it should load about.html. The second time the same element has the class "show," it should open wor ...

Scan for every header tag present and verify the existence of an id attribute within each tag. If the id attribute is absent, insert

Looking to locate all header tags within the content and verify if each tag has an id attribute. If not, then jQuery should be used to add the id attribute. Here is the code snippet: var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); $.each( ...

Issue with the functionality of Bootstrap 5 dismissable alert needs to be addressed

I encountered an issue with the alert in my html code: <div class="alert alert-success alert-dismissible fade show d-flex align-items-center justify-content-center" id="alert" style="display:none;"> <button type=& ...

Is it possible to generate a "pop-up" window upon clicking on the register button?

As a backend programmer, I'm looking to create a popup window that appears in front of the current window when users click "register", eliminating the need for redirection to another page. I believe you understand the concept. How can I achieve this? ...