Unable to access variables of nested components in Angular 2 templates

Recently delving into Angular2, I've encountered a simple issue.

My aim is to create a basic parent component that acts as a container for dynamic boxes, each with its own properties and data.

Here's what I've accomplished so far:

The container class:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {IONIC_DIRECTIVES} from 'ionic-angular';
import {MainBox} from './../../component/main-box/main-box.component';

@Component({
  selector      :   'wrapper',
  templateUrl   :   'build/component/main-container/main-container.component.html',
  directives    :   [IONIC_DIRECTIVES, MainBox]
})

export class MainContainer {
  boxes : MainBox[] = [
    {title : "mor"},
    {title : "naama"}
  ];
  constructor() {

  }
}

The container template

<div>
    <main-box *ngFor="let box of boxes"></main-box>
</div>

** main-box represents each individual box

MainBox class:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {IONIC_DIRECTIVES} from 'ionic-angular';

@Component({
  selector      :   'main-box',
  templateUrl   :   'build/component/main-box/main-box.component.html',
  directives    :   [IONIC_DIRECTIVES]
})

export class MainBox {
  title:any;
  constructor() {
  }
}

Box Template

{{title}}

Assumedly, Angular should display the correct title automatically, yet it appears blank.

However, by implementing the following:

<div *ngFor="let box of boxes">{{box.title}}</div>

I am able to view the title accurately, although I prefer to keep the template files entirely separate.

Thank you!

Answer №1

When working with Angular components, it is important to pass data explicitly to children components:

<div>
    <custom-box *ngFor="let box of boxes" [header]="box.title"></custom-box>
</div>
export class CustomBox {
  @Input() header: any;
  constructor() {
  }
}

Answer №2

If you want to see the title within the main box, you must supply the title as an input

   <div *ngFor="let box of boxes">
             <main-box [title]="box.title"></main-box>
   </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

Pass an array of objects to an Angular 8 component for rendering

Recently, I started working with Angular 8 and faced an issue while trying to pass an array of objects to my component for displaying it in the UI. parent-component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

Encountering a 404 Error in Angular 17 When Refreshing the Page

After completing my Angular 17 project and deploying it to hosting, I encountered an issue where pressing F5 on the page would redirect me to a 404 error page. Despite searching for solutions, I was unable to resolve this situation within Angular 17. I am ...

How to conceal an element in Angular using its unique identifier

I am looking for a way to toggle the visibility of an element based on its ID. I have a dynamic list with the following structure in my TS component: vehicles = [ { "id": 1, "type": "car", ...

Managing state in NGRX entities can be simplified by learning how to assign action.payload to a state property in Ups

In the entity state, I have a reducer that needs to assign action.payload.Message to saveMessage.msg when carrying out upsertOne on the UPSERT_Message_SUCCESS action. export interface MessageState extends EntityState<Message> { // additional enti ...

Could one potentially assign number literals to the keys of a tuple as a union?

Imagine having a tuple in TypeScript like this: type MyTuple = [string, number]; Now, the goal is to find the union of all numeric keys for this tuple, such as 0 | 1. This can be achieved using the following code snippet: type MyKeys = Exclude<keyof ...

How to extract component prop types in Vue 3 with typescript for reusability in other parts of your application

When you specify the props under the "props:" key of a Vue component, Vue can already automatically determine their types, which is quite convenient. However, I am wondering if there is an utility type in Vue that can be used to extract the props' ty ...

Using HttpClient to make a POST request to a json file on a local server

I have a `data.json` file located in the assets folder of my Angular application. The file path is as follows: MyApp => src => assets => data.json I am trying to make a `POST` request to this file using HttpClient in a component within the app ...

Contrary to GraphQLNonNull

I am currently working on implementing GraphQL and I have encountered a problem. Here is an example of the code I wrote for GraphQL: export const menuItemDataType = new GraphQL.GraphQLObjectType({ name: 'MenuItemData', fields: () => ...

Typescript throwing error TS2307 when attempting to deploy a NodeJS app on Heroku platform

Encountering an error when running the command git push heroku master? The build step flags an error, even though locally, using identical NodeJS and NPM versions, no such issue arises. All automated tests pass successfully without any errors. How can this ...

What could have caused the sudden halt of fetching on all server branches in the backend?

Following a code refactor on a separate branch, the fetch function ceases to work in any branch despite everything else functioning correctly. The error message reads: ...server/KE/utils.ts:44 const response = await fetch( ^ ReferenceError ...

Disable the functionality of the device's back button to prevent it from going back to the

For my project, I utilize popups to display important information to the user. When a popup is displayed, how can I override the functionality of the device's back button so that instead of navigating to the previous route, it will close the popup? ...

Using TypeScript to transform a tuple type into an object

When dealing with a tuple type like: [session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string] there is a need to convert it ...

Using MSAL for authentication in combination with NGRX for state management

I am currently using MSAL login, which automatically redirects to the Microsoft login page. However, when I set the cache location to 'none' instead of 'localStorage', it is not redirecting. I prefer not to store the token in local sto ...

Updating Elements in an Array Using JavaScript is Not Functioning as Expected

In my Angular application, I have included some lines of TypeScript code which involve Boolean variables in the constructor and an array of objects. Each object in this array contains input variables. selftest: boolean; failed: boolean; locoStateItem ...

Utilizing the combination of attribute binding and string interpolation

Looking to create an accordion similar to the one showcased on the Bootstrap website, but with the twist of dynamically loading data using Angular 2's *ngFor directive. I attempted setting the value of aria-controls dynamically like so: [attr.aria-co ...

Typescript input event

I need help implementing an on change event when a file is selected from an input(file) element. What I want is for the event to set a textbox to display the name of the selected file. Unfortunately, I haven't been able to find a clear example or figu ...

Retrieving the event name from a CustomEvent instance

Looking to retrieve the name of a CustomEvent parameter in a function, which is basically the string it was created with (new CustomEvent('foo')) If you need a reference, check out https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent ...

What causes interface to generate TS2345 error, while type does not?

In the code below: type FooType = { foo: string } function fooType(a: FooType & Partial<Record<string, string>>) { } function barType(a: FooType) { fooType(a) } interface FooInterface { foo: string } function fooInterface(a: FooInt ...

Troubleshooting an issue with a Typescript React component that is generating an error when using

I am in the process of implementing unit testing in a Typescript and React application. To start off, I have created a very basic component for simplicity's sake. import React from "react"; import ReactDOM from "react-dom"; type T ...