Having difficulty grasping the reason for the databinding issue in Angular 6

Hey there,

I'm relatively new to working with Angular 6 and currently in the process of building my own website using Angular+NodeJs.

The interface I'm creating consists of 2 sections each containing 3 buttons. When a button is clicked, it triggers a modal that displays a title (corresponding to the button's name) and a body (an array of paragraphs with content). This information, including section title, button names, and modal body, is sent from the node server as a JSON string.

While everything functions properly on the server side, I am facing an issue on the front end. The JSON string is successfully transmitted when the service makes the query, and the button titles are displayed correctly on the screen alongside the modal title. However, the modal body fails to show up.

I am trying to comprehend why the modal title appears correctly, but the modal content does not, even though I believe I have used similar code for both. It seems like there might be a fundamental misunderstanding about databinding on my part.

Here's a snippet of my JSON:

[
        {id:1, title: "section title ...", buttons:[
          {
            id:1,
            text:"Button title 1",
            paraphs:[
              {id:1, content:"paraph1"},
              {id:2, content:"paraph2"}
            ]
          },
          {id:2, text:"Button title 2"},
          {id:3, text:"Button title 3"}
        ]},
        {id:2, title: "Section title 2", buttons:[
          {id:1, text:"Button title 1"},
          {id:2, text:"Button title 2"},
          {id:3, text:"Button title 3"}
        ]}
      ]
    

This is how my component.html looks like:

<!-- Your HTML code here -->

And here's a snippet of my component.ts file:

import { Component, OnInit } from '@angular/core';
import { PrestationService} from '../service/prestation.service'

@Component({
  selector: 'app-prestation',
  templateUrl: './prestation.component.html',
  styleUrls: ['./prestation.component.css']
})
export class PrestationComponent implements OnInit {


  sections;
  modal_title;
  paraphs;


  constructor(private ps:PrestationService) { }

  ngOnInit() {
    this.ps.getPrestation().subscribe(
      data => this.sections = data
    )
  }

  handleClick(buttonTitle, buttonContent){
    this.modal_title = buttonTitle;
    this.paraphs = buttonContent;
  }



}

Answer №1

There are a few issues to address in this code snippet:

<div class="modal-body" ngFor="let paraph of paraphs" *ngIf="!paraphs==undefined">
  <p>{{paraph.content}}</p>
</div>
  1. The ngFor directive should have an asterisk preceding it (should be *ngFor)
  2. Avoid mixing multiple structural directives on the same element as stated in the Angular documentation (source)
  3. The condition used is quite unusual and likely will never evaluate to true based on the logical operations applied.

Consider removing the *ngIf altogether since iterating over an empty array will not produce any results:

<div class="modal-body" *ngFor="let paraph of paraphs">
  <p>{{paraph.content}}</p>
</div>

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 facing an issue with calling a controller from an HTTP GET request in ASP.Net Core 6 using a Single Page Application (SPA) endpoint

[UNSOLVED] - Seeking help from developers [Issue] As a newcomer to the industry, I apologize for my lack of experience in advance. I am currently facing a challenge with ASP.Net Core 6 and it seems like I am missing something simple, but I can't see ...

Transform current JSON data into formatted JSON format using JavaScript or TypeScript

I have a JSON structure that needs to be reformatted in order to meet the requirements of an external service. Although the current format is complex and cannot be altered, I need to modify it to match the desired output for the external service. Current ...

Modifying a Component's Value in its Template Based on an IF Condition in Angular 6

How can I display or hide the 'separator-container' based on a specific condition in the row data? The condition to satisfy is mentioned as "myConditionCheck" in the 5th line of code. I attempted to achieve this by using "isWarningSeperatorVisib ...

The interaction between Web API, Angular, and the unique MAC Address

My organization currently operates an Application using ASP MVC. However, the application is experiencing slow performance and confusion due to multiple programmers with conflicting ideas. I have taken on the task of refactoring and migrating it to Angular ...

The 'state' property is not found on the 'FetchPeriod' type

Currently, I am embarking on a journey to grasp ReactJS by following a tutorial provided at this Tutorial. Being a novice in the programming language, I find myself at a loss as to what steps to take next. One roadblock I encountered was when attempting ...

Obtaining user profile pictures from Graph API for several users at the same time with the help of RxJs

I have created an ASP.NET Core API that can provide a list of users to an Angular service. The user data returned consists of certain properties like id, firstName, and lastName. My aim is for the Angular service to first fetch this user list from my API ...

Tips for effectively constructing and optimizing an Angular 5 Project

As a newcomer to an Angular 5 project, I recently executed the command ng build --prod which resulted in the generation of a dist/ folder. To my surprise, the building process took significantly longer than expected. Upon inspecting the contents of the di ...

Blending i18n JIT and AOT in Angular 6

Currently, it appears that the development environment is utilizing Just-In-Time (JIT) compilation while production is using Ahead-Of-Time (AOT) compilation, which is expected behavior. However, an issue arises when attempting to retrieve the LOCALE_ID in ...

What is the best way to include multiple targets/executables within a single Node.js repository?

My React Native app is developed using TypeScript, and I want to create CLI tools for developers and 'back office' staff also in TypeScript. These tools should be part of the same monorepo. After attempting to do this by creating a subfolder wit ...

What methods can TypeScript use to accommodate this kind of Generic Type?

It appears that there is already an existing GitHub issue related to this topic. You can find it here: ts#1213. This type of usage resembles a high-order function, and I am unsure if TypeScript supports it. Although the interface remains the same, there ...

Notifying users when a document is nearing its expiration date in the most effective manner

In my calendar app, I set appointments to automatically delete after 5 minutes. Now, I want to retrieve all appointments that are about to expire within 1 minute and send a notification to the front-end indicating their impending expiration. Although I at ...

Testing vue-router's useRoute() function in Jest tests on Vue 3

Struggling with creating unit tests using Jest for Vue 3 components that utilize useRoute()? Take a look at the code snippet below: <template> <div :class="{ 'grey-background': !isHomeView }" /> </template> &l ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

Currently in the process of modernizing an outdated method to a more up-to-date version in Jasmine, encountering issues related to

Currently working to update the method throwOnExpectationFailure to the newer one oneFailurePerSpec. According to the Jasmine documentation, this can be achieved by: Use the `oneFailurePerSpec` option with Env#configure After conducting research, I came ...

Error: The URL constructor is unable to process /account as a valid URL address

Working on a new social media app using appwrite and nextjs, encountering an error "TypeError: URL constructor: /account is not a valid URL" upon loading the website. Here's the current file structure of my app: File Structure Below is the layout.tsx ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

Retrieve the data from a JSON file using Angular 4

I have a JSON data structure that looks like this: [{"id": "ARMpalmerillas07", "type": "GreenHouse","act_OpenVentanaCen": {"type": "float", "value": 0, "metadata": {"accuracy": {"type": "Float", "value": "07/02/2018 13:08 : 43 "}}}, "act_OpenVentanaLatNS" ...

Extract the event.data value from a window.addEventListener (MessageEvent) in order to trigger a separate function

Currently, I am delving into Angular and aiming to develop a LinkedIn Login API. To achieve this, I'm utilizing window.open to launch a new window where the user can either accept or decline the authorization. Upon successful acceptance, LinkedIn retu ...

Clipanion is unable to fulfill requests

I followed the official Clipanion documentation for creating a CLI tool () and even cloned an example from here - https://github.com/i5ting/clipanion-test, but I'm facing issues when trying to execute my commands. It seems like I might be struggling ...

Failed attempt to install Angular Material

On my Windows laptop, I am currently using the following versions: Angular CLI: 9.1.15 Node: 16.16.0 OS: win32 x64 Windows 10 When I try to add Angular Material using the command ng add @angular/material, it runs without any issues. However, after the i ...