Importing components with local data within an ngFor in Angular TypeScript

Having recently started working with Angular2, I am facing a challenge with importing components in ngFor loops.

The issue seems to arise when importing components with data in ngFor loops; it checks for values in the .ts file instead of the local variable used in ngFor. My goal is to pass the variable used in ngFor to the next component.

accommodations.component (parent view)

ts:

import { Component, Input } from '@angular/core';
import { AccommodationModel } from '../../../../models/reservations/accommodation-model';

@Component({
    selector: 'reservations-reservation-accommodations',
    templateUrl: './accommodations.component.html'
})

export class AccommodationsComponent {
    constructor() { }

    @Input() accommodations: AccommodationModel[];
}

html:

<div class="card-block">
                <ngb-tabset>
                    <ngb-tab *ngFor="let accommodation of accommodations" title="{{accommodation.arrivalDate}}">
                        <ng-template ngbTabContent>
                            <div class="table-responsive">
                                <table class="table table-condensed table-bordered table-striped content-divider-up">
                                    <thead>
                                        <tr>
                                            <th>Arrival Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                {{accommodation.arrivalDate}}
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </ng-template>
                    </ngb-tab>
                </ngb-tabset>

                <reservations-reservation-accommodations-costs [costs]="accommodation.costs"></reservations-reservation-accommodations-costs>
            </div>

costs.component (child view)

ts:

import { Component, Input } from '@angular/core';
import { CostModel } from '../../../../../models/reservations/cost-model';

@Component({
    selector: 'reservations-reservation-accommodations-costs',
    templateUrl: './costs.component.html'
})

export class CostsComponent {
    constructor() { }

    @Input() costs: CostModel[];
}

html:

<div class="row content-divider-up">
    <div class="col">
        {{costs.length}}
    </div>
</div>

How can I effectively pass let accommodation(.costs) in ngFor to costs.component? The issue I'm encountering is that costs always appears as undefined in costs.component, as it searches for a variable named "accommodation" in the accommodations.components.ts file which is not the desired behavior.

Answer №1

<reservations-reservation-accommodations-costs [costs]="accommodation.costs"></reservations-reservation-accommodations-costs>

lodging serves as a local template reference within the loop, and using it beyond its scope will result in an undefined error. To address this, make sure to place it inside the loop for proper definition.

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

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

Retrieve upcoming route details within canDeactivate guard in the updated Angular2 router

Is there a way to retrieve the upcoming route information within the "canDeactivate" guard of Angular 2's new router? ...

Setting the Formgroup status to Invalid will only occur if there are errors in multiple fields, not just one

I'm having an issue with my form where setting passportrank as error does not change the formgroup status to Invalid. Additionally, when I navigate to the next section, the inline error message of "You are not eligible" also gets cleared. ngOnInit() ...

Ways to monitor a variable for changes and automatically update the value in related components

I feel like I may not be following best practices, so I'm hoping for some guidance. Within a provider, there is a variable that I have defined. @Injectable() export class SharedService { public mynumberservice:any=0; In both the MainComponent an ...

Angular 4: Unhandled error occurred: TypeError - X does not exist as a constructor

I am currently developing a project in Angular 4, and I encountered an error while running the application. The specific error message is as follows - ERROR Error: Uncaught (in promise): TypeError: index_1.EmployeeBase is not a constructor TypeError: in ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

Steps for incorporating the pull-to-refresh feature in CDK virtual scrolled Angular application

My current setup involves using CDK virtual scroll in the DOM, however I have encountered a glitch when scrolling quickly. To address this issue, I am considering implementing the Pull to Refresh method. Can anyone provide guidance on how to implement Pu ...

Encountering issues when passing a string as query parameters

How can I successfully pass a string value along with navigation from one component to another using query parameters? Component1: stringData = "Hello"; this.router.navigate(['component2'], { queryParams: stringData }); Component2: ...

Possibility for Automatic Type Inference in Generics

Is there a way to have a method infer the type of function parameter without specifying its generic? Currently it is 'GET' | 'POST', but I only need the literal 'GET' const func = <Params, Method extends "GET" | & ...

How to implement SVG in React with the image source as a parameter?

I've been working on a React component in NextJS that displays an image inside a hexagon. The issue I'm facing is that when I try to use multiple instances of this component with different images in the HexagonWall, all hexagons end up displaying ...

What is the significance of the message "JavaScript files do not have any valid rules specified"?

I am working on a React - Typescript project that was created using the following command: create-react-app my-app --scripts-version=react-scripts-ts While it compiles without any issues, I keep receiving a message or warning that says: No valid rules h ...

The element 'fontFamily' is not recognized within the 'ThemeOptions' type in MUI theming

I'm diving into the world of React and MUI by building my own dashboard from scratch. Let's take a look at my App.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; i ...

What exactly is a NativeScript app: is it the experience users have on their mobile devices, or the product they download from the app store?

Currently, I am diving into the world of Angular and exploring how to develop Angular applications with TypeScript while working on a C# ASP.Net Core Web Api project as the server side component. My question is this - if I create a NativeScript app in add ...

Issue with Pop Up not redirecting correctly after a successful login in Azure AD

I recently integrated Azure AD with my web application. When clicking on the login window, a pop-up appears with the URL . It prompts for the Azure AD username and password. However, after successfully logging in, a code is returned as a parameter but the ...

Tips for sending data to CSS in Angular

I have an Angular application where I need to calculate the width of an element and store it in a variable called finalposition. Then, I want to move this element to the left by (finalposition)px when hovering over it. How can I achieve this styling effect ...

Creating a consolidated System.config mapping for @angular modules using a single .js file

Currently in the process of developing an Angular 2 application, with the specific requirement to consolidate all resulting Javascript files into a single .js file called output.js. Now, the challenge is to incorporate map configuration within System.conf ...

Looping through an array of objects with Angular 4's ngFor directive to dynamically display content

I am working with Angular 4 and I am attempting to iterate through an array of objects to present the data in Angular Material grid tiles. The code snippet from my HTML file (app.component.html) is as follows: <div class="list" *ngIf="listContacts == t ...

Sundays and last days are excluding React-big-calendar and dayjs longer events from being displayed

I've encountered a bug in my calendar view implementation. Long events are not displaying on Sundays or the ending day. Please refer to this image for reference: https://i.stack.imgur.com/V0iis.png Event details: Start time: Mon Aug 07 2023 15:44:00 ...

How can I make my webpage fill the entire width of an iPhone screen when in landscape mode using Angular or React?

While testing my website on my iPhone, I noticed a significant gap appearing on either side of the app in landscape view in Safari. Is there a solution to fix this issue? The problem occurs in both Angular and React applications, examples of which are disp ...

The UploadFile Interface seems to be missing

Can someone clarify whether the @UploadedFile decorator's interface is predefined or if I need to define it myself? ...