Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data.

 data = ['middlename.firstname.lastname','firstname.lastname']; 

During the process, I am looping through the .html using the following approach:

<div *ngFor="let x of data">

   <p *ngIf="x.indexOf('.')!==1">
       {{x.split('.')[1]}}
   </p>

</div>  

However, I am encountering an issue here. In the data, there is "'middlename.firstname.lastname" where 'middle name' acts as the parent and the rest are children. On the frontend, I display the position 1, which works fine in this case. But in the second data "firstname.lastname", there is no parent specified, so it displays based on the position as "Lastname". My intention is to display the firstname even when there is no parent mentioned.

Below you can find the Stackblitz URL for reference:

https://stackblitz.com/edit/angular-jmdaxg

Present output :
          firstname
          lastname
expected output :
          firstname
          lastname

Answer №1

From my perspective, it would be best to construct the appropriate data structure within your component and then proceed to display it.

    dataToDisplay = this.data.reduce((acc, elem) => {
        if (elem.indexOf('.') !== 1) {    
          let nameSplit = elem.split('.');
          if (nameSplit.length === 2) {
            acc.push(nameSplit[0]);
          }
          else if (nameSplit.length === 3) {
            acc.push(nameSplit[1])
          }
         return acc;
       }
    }, []);

Afterwards, you can iterate over dataToDisplay in your HTML to showcase the results

<div *ngFor='let x of dataToDisplay'>
  <p>{{x}}</p>
</div>

Alternatively, if you prefer handling this in your HTML, you could implement something like:

<div *ngFor="let x of data">
   <p *ngIf="x.indexOf('.')!==1">
       <ng-container *ngIf="x.split('.').length === 2">
          {{x.split('.')[0]}}
       </ng-container>
       <ng-container *ngIf="x.split('.').length === 3">
          {{x.split('.')[1]}}
       </ng-container>
   </p>
</div> 

You can view an example here: https://stackblitz.com/edit/angular-nkqxxa

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

I am looking to implement tab navigation for page switching in my project, which is built with react-redux and react-router

Explore the Material-UI Tabs component here Currently, I am implementing a React application with Redux. My goal is to utilize a panelTab from Material UI in order to navigate between different React pages. Whenever a tab is clicked, <TabPanel value ...

Increase the date and time by a specified number of days

After searching for solutions on how to add a specific number of days to a given date, I came across various methods. However, my requirement is to add days to both Date and Time in the format MM-DD-YYYY HH:MM:SS. I attempted a method which worked fine wh ...

How do you structure `en.js` or `ja.js` files for lazy loading in vue-i18n?

What is the correct format for lazy loading en.js or ja.js? The code below is not working: // en.js export default { title: 'Title', greeting: 'How are you' }; and import Vue from 'vue'; import Inven ...

Filtering a key-value pair from an array of objects using Typescript

I am working with an array of objects containing elements such as position, name, and weight. const elements = [{ position: 3, name: "Lithium", weight: 6.941, ... },{ position: 5, name: "Boron", weight: 10.811, ... }, { position: 6, name: "Carbon", weight: ...

Unlock the parent of an unnamed iframe

Here's a scenario: <div id="parent"> <iframe....></iframe> </div> If I had the above structure, I could use window.parent.document.getElementById('parent').innerHTML to access it. However, my current situation is di ...

Utilizing HTML5/JavaScript to send a text message from a mobile device

I am developing a mobile web application to be downloaded from various markets with a mini web server, capable of running on any operating system such as iOS, Android, Windows8, and more. My goal is to make the application as OS-independent as possible by ...

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...

Having trouble toggling classes with mouseup in Wordpress Underscores theme

While I'm utilizing Underscores as the foundation theme for my website, one aspect that I particularly appreciate is its incorporation of a functional mobile navigation component. However, since my site is essentially single-page, the navigation remai ...

Gatsby no longer hosts the website locally during certain tasks

My React and Gatsby project runs smoothly when I use Yarn start, it builds everything and serves the project on http://localhost:8000. However, whenever I perform specific operations like going to a 404 page or opening Chrome Dev tools, it suddenly stops s ...

Failed attempt to perform Ajax requests for REST API data

I am currently working on developing an application that requires a login through a REST API to retrieve a session id. To achieve this, I have set up a button that triggers a JavaScript function for making an AJAX call to authenticate the user. The result ...

Irritating Popup - (or perhaps a more elegant alternative)

My current challenge involves tracking the time a user spends with a specific window in focus. I aim to record this duration accurately and pause the timer when the user switches to another window, then resume it upon returning. Ultimately, I want to measu ...

What could be causing the error "Type 'String' cannot be used as an index type" to appear in my TypeScript code?

My JavaScript code contains several associative arrays for fast object access, but I'm struggling to port it to TypeScript. It's clear that my understanding of TypeScript needs improvement. I've searched for solutions and come across sugges ...

Node.JS 3DES encryption encountering an issue with IV length validation

I'm new to working with Node.js and I've encountered an issue with the encryption object: var des3_key = new Buffer("redacted", "base64"); // obtained from another source var des3_iv = new Buffer("alsoredacted", "base64"); // obtained from anoth ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

Show the total sum of a specific column in a datatable and enable the option to export the data to an Excel

When exporting a datatable as an Excel file with 4 columns, the third column contains product prices. After the export, I would like to see an additional row at the end of the table labeled "Total" that displays the sum of all values in column 3. I initia ...

Understanding the mechanism of callback function in NodeJS within the context of routes and controllers

Trying to grasp the concept of callbacks and puzzled by the recurring issue TypeError: callback is not a function Here's my router setup: // getPriceRouter.js router.post('/getPrice', function(req, res) { priceController.getPrice(req, ...

Adding an object to an array in Postgres with TypeORM

I am currently facing an issue with the column in my Postgres database that has a data type of json. The code snippet for this scenario is as follows: @Column({ type: 'jsonb', nullable: false, default: [] }) us ...

Simply touch this element on Android to activate

Currently utilizing the following code: <a href="http://www...." onmouseover="this.click()">Link</a> It is evident that this code does not work with the Android Browser. What javascript code will function properly with the Android Browser as ...

Guide to utilizing various Nodelists using the forEach function

I'm currently developing an online store project that includes a shopping cart feature. My goal is to send a POST request to the server with the items selected by the user in the cart. I have initialized an empty array and I have 3 Nodelists containin ...

Exploring the Worldwide Influence of TypeScript, React, and Material-UI

I am currently following an official tutorial on creating a global theme for my app. In my root component, I am setting up the global theme like this: const themeInstance = { backgroundColor: 'cadetblue' } render ( <ThemeProvider theme ...