Display an array depending on the value in Angular 2 when clicked

In my current Angular 2 project, I am dealing with a .json file structured like this:

{
    "PropertyName": "Occupation",
    "DefaultPromptText": "occupation text",
    "ValuePromptText": {
        "WebDeveloper": "for web developer",
        "Administrator": "for admin"
    }
},
{
    "PropertyName": "FirstName",
    "DefaultPromptText": "first name text",
    "ValuePromptText": ""
}

To retrieve this file, I have set up a service as follows:

import { Injectable } from "@angular/core";
import { Http } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class PromptService {

constructor(private http: Http) { }

fetchPrompts() {
    return this.http.get('/temp.json').map(
        (Response) => Response.json()
    );
}

}

The form inputs in my HTML are designed like this:

<fieldset class="one-quarter sm-padding">
<label>First name</label>
<input name="FirstName" placeholder="Firstname" type="text" tabindex="1" required>
</fieldset>

<fieldset class="one-quarter sm-padding">
<label>Occupation</label>
<input name="Occupation" placeholder="Occupation" type="text" tabindex="2" required>
</fieldset>

<div class="prompt-bubble active md-padding bottom-sm-margin">
<h2>Help Text</h2>
<ul>

    <li *ngFor="let promptText of promptTexts">

        <p>{{promptText.DefaultPromptText}}</p>

    </li>

</ul>

</div>

The component.ts file has the following code:

import { Component, OnInit } from '@angular/core';
import { PromptService } from '../../services/prompt.service';

@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [PromptService]
})

export class HomeComponent implements OnInit {


promptTexts = [];

constructor(private promptService: PromptService) { }

ngOnInit() {
    this.promptService.fetchPrompts().subscribe(
        (data) => this.promptTexts = data
    );
}

}

I aim to display a specific array based on whether the 'PropertyName' value matches the input name. For instance, clicking on the 'FirstName' input should show the array with 'PropertyName' equal to "FirstName" and include the corresponding 'DefaultPromptText.'

Please let me know if you need further clarification.

Thank you!

Answer №1

Consider using **ngIf** for this situation

<input name="FirstName" [(ngModel)]="firstName" placeholder="Firstname" type="text" tabindex="1">

Additionally,

<ul *ngIf="yourFetchData && firstName === promptTexts.PropertyName">
    <li *ngFor="let promptText of promptTexts">
        <p>{{promptText.DefaultPromptText}}</p>
    </li>
</ul>

<ul *ngIf="!yourFetchData || firstName !== promptTexts.PropertyName">
    <li *ngFor="let promptText of promptTexts">
        <p>{{promptText.DefaultPromptText}}</p>
    </li>
</ul>

Note: promptTexts is an object, so you must adjust the code accordingly.

Instead of:

    <li *ngFor="let promptText of promptTexts">
        <p>{{promptText.DefaultPromptText}}</p>
    </li>

Use:

   <p>{{promptTexts.DefaultPromptText}}</p>

In case of a list:

<ul>
    <li *ngFor="let promptText of promptTexts">
        <p>{{(firstName === promptText.PropertyName) ? promptText.DefaultPromptText : 'whatever'}}</p>
    </li>
</ul>

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

Troub3leshooting Circular Dependency with Typescript, CommonJS & Browserify

I am currently in the process of transitioning a rather substantial TypeScript project from internal modules to external modules. The main reason behind this move is to establish a single core bundle that has the capability to load additional bundles if an ...

Compilation of various Typescript files into a single, encapsulated JavaScript bundle

After researching countless similar inquiries on this topic, I have come to the realization that most of the answers available are outdated or rely on discontinued NPM packages. Additionally, many solutions are based on packages with unresolved bug reports ...

NGRX Angular does not support iteration of state.data

I'm attempting to combine state.data with payload.data but encountering an error: TypeError: state.data is not iterable This is my code snippet: on(apiActionGroup.success, (state, payload) => newState(state, { data: { [payload.page?.toStrin ...

Query data from a different table in PostgreSQL based on elements in an array and present the results in a specific order

I have a database table containing various parts, each with a unique ID and serial number assigned by the manufacturer. These parts are then used to build assemblies, with the sequence of assembly being crucial. Once an assembly is created, a new entry is ...

What could be the reason for my provider loading the data twice?

Recently, I have been following a tutorial on building an Ionic app that displays information about National Parks. The data is stored locally and loaded by a Provider in my application. However, I noticed that the data is being loaded twice by the Provide ...

Combining scatter chart series with candlestick chart in Angular Google Charts

I have incorporated Angular Google Charts to present candlesticks charts. Currently, it appears like this: https://i.sstatic.net/Q090H.png My goal is to include points that signify buy and sell orders for my backtesting. Just like this example: https:// ...

Dealing with inconsistent wait problems in Angular applications with Protractor and Jasmine

In my current project, I am using Angular for building the application along with Protractor and Jasmine for e2e tests. However, we have been experiencing inconsistent test script failures during execution. To tackle this issue, we tried setting ignore.s ...

removing the mapStateToProps function will result in an undefined value

I am new to React and I'm in the process of converting a class component to functional components using hooks. I need some guidance on safely removing 'mapStateToProps' without encountering undefined errors. I have two pages, A.js and B.js. ...

Retrieve numerous rows by utilizing the forthcoming SQL Server TSQL command for extracting data from JSON format

I'm attempting to fetch multiple rows using the SQL Server 2017 TSQL code from a JSON object. DECLARE @json NVARCHAR(MAX); SET @json = N'{ "DateCreated": "2020-08-02T16:04:59.3558001+01:00", "Name": "Bolts&q ...

Having trouble converting my form data into an array for table display

My website has a form for entering dummy patient information, with a table to display the submitted data. However, I'm facing an issue where the data is not being stored in the array when the user clicks the "Add Patient" button. Upon checking the arr ...

Retrieve an Array Containing a Mix of Objects and Functions in Typescript

Let's address the issue at hand: I spent several months working with a custom React Hook using plain JavaScript, and here is the code: import { useState } from 'react'; const useForm = (initialValues) => { const [state, setState] = ...

Sending updated data from modal back to child component

Within my parent component, I have two child components: Child0 and Display. Child 0 consists of a single button that triggers the opening of a modal where users can select items from a list. The Display component, on the other hand, only contains a label ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...

What is the process for importing a component at a later time?

I am attempting to import components with a delay in a seamless manner. My goal is to import the components discreetly so that they load smoothly in the background while viewing the homepage. I experimented with lazy loading, but found that it caused dela ...

Creating a custom hook to detect when multiple elements are hovered over

I am currently working on creating a hook that can identify when hover is triggered over specific buttons. Here is what I have so far: enum options { buttonOne: 'buttonOne', buttonTwo: 'buttonTwo' } type HoverType= { [key in opti ...

The final value of a loop is consistently returned each time

Creating a loop to generate objects. Action.ts public campaing:any = { 'id': '', 'campaing_code': '', 'campaing_type': '', 'start_date': this.currentDate, 'end ...

Challenges with JavaScript arrays object

I am new to JavaScript and struggling with how to extract data from this array. Can you confirm if it is formatted correctly? Shown below is the console output of the array object: [] 0: Item {id: 0, symbol: "VBIV", boughtDate: "2018-07-22", company: "V ...

Consolidate all REST service requests and match the server's response to my specific object model

My goal was to develop a versatile REST service that could be utilized across all my services. For instance, for handling POST requests, the following code snippet demonstrates how I implemented it: post<T>(relativeUrl: string, body?: any, params?: ...

Using Angular Ionic 3 to apply the disabled attribute

I have a situation in my main.ts where I need to disable a textarea in the HTML if an object is initialized. I've attempted various methods like: ng-attr-disabled="!myObj"; ng-attr-disabled="{myObj!= null}"; and also directly using ng-disabled. I e ...

Using a string array in a JSON model - a simple guide

Just starting out with Angular and having some difficulty integrating my JSON data effectively. Inside my service, I have temporary JSON data that is structured using a model to define the different types of information within it. My objective is to creat ...