Having trouble extracting value from another component or dealing with an architectural issue?

Just recently delving into Angular, I embarked on this journey last week with a small programming foundation. My current project involves creating a simple blog application where I need to pass a value from the root (app.component.ts) to my component tag "app-post-list-item" nested within another component template (post-list-component.html). Unfortunately, despite my attempts at using @Input() in different places, the text doesn't display. There seems to be a missing piece or misunderstanding on my end, and it's all quite overwhelming. I even tried relocating the "post-list-item" folder inside the "post-list" one, but that too proved futile.

Both "post-list" and "post-list-item" serve as child components of "app". Could someone please review my code and provide guidance on how to successfully achieve this? Any insights would be greatly appreciated. Thank you!

Here is the architecture diagram for reference.

Snippet from app.component.html:

<div class="row">
  <div class="col-12">
    <app-post-list></app-post-list>
  </div>
</div>

Extract from app.component.ts:

export class AppComponent {  
  title = 'blogApp';  
  pub1: string = "My first post"; // Desired content to display
}

Snippet from post-list.component.html:

<ul class="list-group">   
  <app-post-list-item [titrePubli]="pub1"></app-post-list-item> <!-- Indicating content to display -->
  <app-post-list-item></app-post-list-item>
  <app-post-list-item></app-post-list-item>
</ul>

Extract from post-list.component.ts:

import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.scss']
})

export class PostListComponent implements OnInit {
  @Input() pub1: string; // Utilizing @Input() here
  constructor() { }
  ngOnInit(): void {  }
}

Snippet from post-list-item.component.html:

<li class="list-group-item">
  <h3 style="font-size: 20px;">Title: {{ getTitrePubli() }}</h3> <!-- Desired location for display -->
  <h4 style="font-size: 18px;">Content: {{ getContenuPubli() }}</h4>
</li>

Extract from post-list-item.component.ts:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-post-list-item',
  templateUrl: './post-list-item.component.html',
  styleUrls: ['./post-list-item.component.scss']
})

export class PostListItemComponent implements OnInit {
  @Input() titrePubli: string;
  contenuPubli: string = "This is some dummy text";

  @Input() pub1: string;

  constructor() { } 

  ngOnInit(): void { }

  getTitrePubli() { return this.titrePubli; }
  getContenuPubli() { return this.contenuPubli; }
}

Answer №1

The screenshot provided depicts the file structure of the project, not its architecture. It is important to ensure that files are correctly referenced within modules and other related files for seamless data sharing.

The root cause of confusion lies in the naming convention. Let's examine a simple line:

<app-post-list [pub1]="pub1"></app-post-list>
                 ˄       ˄
                 |       |
        @Input()         member
        variable         variable
        of post-list     of app-component

In this snippet, [pub1] denotes the input variable of the post-list component while pub1 on the right side represents the value of the member variable ("Ma première publi" in this case).

Although the above pattern is sound, beginners in Angular might benefit from using clearer naming patterns. For instance,

<app-post-list [pub1Input]="pub1Value"></app-post-list>

This distinction in variable names enhances comprehension. Subsequently, the variable is passed again from post-list to post-list-item, as demonstrated in the modified code below:

App component

export class AppComponent  {
  title = 'blogApp';  
  pub1Value: string = "Ma première publi";
}
<div class="row">
  <div class="col-12">
    <app-post-list [pub1Input]="pub1Value"></app-post-list>
  </div>
</div>

Post list component

export class PostListComponent implements OnInit {
  @Input() pub1Input: string;

  titrePubliOne = 'title 1';
  titrePubliTwo = 'title 2';
  titrePubliThree = 'title 3';

  constructor() { }

  ngOnInit() { }
}
<ul class="list-group">   
  <app-post-list-item [titrePubli]="titrePubliOne" [pub1]="pub1Input"></app-post-list-item>
  <app-post-list-item [titrePubli]="titrePubliTwo" [pub1]="pub1Input"></app-post-list-item>
  <app-post-list-item [titrePubli]="titrePubliThree" [pub1]="pub1Input"></app-post-list-item>
</ul>

Post list item component

export class PostListItemComponent implements OnInit {
  @Input() titrePubli: string;
  @Input() pub1: string;
  contenuPubli: string = "C'est le bla bla bla";

  constructor() { }

  ngOnInit() { }
}
<li class="list-group-item">
  <h3 style="font-size: 20px;">Titre : {{ titrePubli }}</h3>
  <h4 style="font-size: 18px;">Contenu : {{ pub1 }}</h4>
</li>

View the working example at: Stackblitz

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

Showing information from a JSON file in a layout

Hey there! I could really use some assistance in displaying my data. So, I've got this custom provider that calls my API, and everything is running smoothly. Currently, I'm focusing on the page titled 'playing', and here's a glim ...

Creating a Build-Free Workflow in a TypeScript Monorepo

Imagine having this monorepo structure: /apps /apps/app1 /apps/app1/src (includes index.ts and various other files and subdirectories) /apps/app1/tsconfig.json /apps/app1/package.json /apps/app2 /apps/app2/src (contains index.ts and many other files an ...

Firestore rule rejecting a request that was meant to be approved

Recently, I came across some TypeScript React code that fetches a firestore collection using react-firebase-hooks. Here's the snippet: const [membersSnapshot, loading, error] = useCollectionData( query( collection(db, USERS_COLLECTION).withConve ...

Production is experiencing a hiccup, however, the site is still up and running. There seems to be

Having an error in production that I can't seem to replicate on my local machine. The error message reads: src/controllers/userController.ts(2,29): error TS2307: Cannot find module '../services/UserService' or its corresponding type declarat ...

Creating a Tree Hierarchy with Angular 4 FormArray

Looking for a demonstration on how to effectively utilize FormArray with a Tree Structure? I am currently working on implementing inline editing for a hierarchical system Although I have managed to make it functional for the initial level, I am facing ch ...

Translating Bootstrap 5 into Angular components for version 13 and above

In Angular, the lack of support for optional host-elements and containerless components means that each component comes with its own div wrapper. However, when designing Bootstrap components, a host-less component (without an extra div) is needed to mainta ...

Comparison: executing an immediately invoked function expression (IIFE) and a separate

During my recent refactoring of some legacy code, I stumbled upon the following example: // within another function const isTriggerValid = await (async () => { try { const triggers = await db.any(getTriggerBeforeBook, { param ...

Trouble arises in AWS Code Pipeline as a roadblock is encountered with the Module

After many successful builds of my Angular project, it suddenly fails to build on AWS Code Build. I reverted back to a commit before any recent changes, but the error persists. When I run ng build --prod locally, it works fine. However, during the pipeline ...

Creating a Typescript version of the mongodb project aggregation functionality

Present scenario: I am currently working on creating a type-safe wrapper for the node-mongodb driver. I am facing challenges in determining the return type for the project aggregation stage. Feel free to check out the TypeScript Playground here class Base ...

Unable to bind click eventListener to dynamic HTML in Angular 12 module

I am facing an issue with click binding on dynamic HTML. I attempted using the setTimeout function, but the click event is not binding to the button. Additionally, I tried using template reference on the button and obtaining the value with @ViewChildren, h ...

Exploring the Features of Angular 6 through Interface Properties

Is there a way to add a description attribute to a property, similar to the data descriptions in dot net? For example: interface ModuleStatus { [Description "Module state"] moduleStateSymbol: string; [Description "Module type"] moduleTypeS ...

Can you explain the reference to "ng2" in relation to Angular 2?

In countless blog posts discussing Angular 2, I often come across references to ng2. Can someone clarify what ng2 stands for? Is it the CLI for Angular 2? ...

Encountering an issue while attempting to initiate a nested array: "Cannot assign a value to an optional property access in the left-hand side of an assignment expression."

I am dealing with an object that contains nested arrays, structured like this: export class OrdenCompra { public id?: number, public insumos?: OrdenCompraInsumo[], } export class OrdenCompraInsumo { id?: number; traslados?: IImpuestoTraslado[]; } export ...

Capture and store the current ionic toggle status in real-time to send to the database

I have a list of names from the database that I need to display. Each name should have a toggle button associated with it, and when toggled, the value should be posted back to the database. How can I achieve this functionality in an Ionic application while ...

Why does Primeng Lazy loading trigger multiple times when updating the sortField and sortOrder?

Lazyload has been successfully integrated into my primeng-table, <p-table #dataTable [columns]="tableHeader" [value]="tableData" [rows]="10" [paginator]="true" [rowsPerPageOptions]="rowsPerPage" [totalRe ...

Using Angular 2's ngFor directive to iterate through arrays with access to first, last

In this example, I am attempting to make the first occurrence the default: plunkr However, I encountered the following error: Unhandled Promise rejection: Template parse errors: TypeError: Cannot read property 'toUpperCase' of undefined ...

Tips for adjusting the size of a textarea to perfectly fit within a table cell

I have a textarea displayed within an input in a table, but I am looking to resize it so that it completely fills the table cell up to the borders. Here is the logic: <textarea type="textarea" value="{{data.directRowNo}}" id = " ...

Please ensure that the property name is a valid type, such as 'string', 'number', 'symbol', or 'any'

Can anyone help me convert this JavaScript file to Typescript? import React, { useState } from 'react'; import { Button } from './Button'; import { Link } from 'react-router-dom'; import './Navbar.css'; import Settin ...

Having trouble retrieving documents from a nested collection in Firebase

I am attempting to retrieve all documents from Firebase that are based on a query. Here is my current firebase structure: https://i.stack.imgur.com/tXrX8.png Even though I have two documents inside the "ListaFavorite" collection, when I check using empty ...

Adding query parameters to an Angular route

In my app's routing module, I have set up the following routes: const routes: Routes = [ { path: "", redirectTo: "/smart-parking/dashboard", pathMatch: "full" }, { path: "locations-create", component: AddLoc ...