Connect the HTML link component tag to a component that is passed through the constructor

I have recently started learning about Angular and TypeScript.

Within my AppComponent HTML file, I include another component using the code

<app-listpost></app-listpost>

In the TypeScript file, I import the ListPostComponent into my AppComponent to call a specific function within that component from AppComponent.

This function is responsible for adding an object to an array in ListPostComponent

Upon testing, I discovered that while calling the function from AppComponent works, the array manipulated by AppComponent is separate from the one used in the ListPostComponent instance created with the HTML tag.

app.component.html

<div style="text-align:center">
  <h1>
    {{ getTitle() }}
  </h1>
</div>
<app-listpost></app-listpost>
<button class="btn btn-success" (click)="addPostToList('test title from AppComponent', 'test content from AppComponent')">Add test post</button>

app.component.ts

import { Component } from '@angular/core';
import { ListpostComponent } from './listpost/listpost.component'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers:[ListpostComponent]
})
export class AppComponent {
  title = 'Exercise';

  constructor(private listPostComp: ListpostComponent){}

  public addPostToList(newTitle, newContent){
    this.listPostComp.addPostToList(newTitle, newContent);
  }

  getTitle(){
      return this.title;
  }
}

listpost.component.html

<button class="btn btn-success btn-test" (click)="addPostToList('test title from ListPostComponent', 'test content from ListPostComponent')">Add test post</button>
<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <ul class="list-group">
                <app-post   *ngFor="let post of getListPosts()"
                            [Title]="post.title"
                            [Content]="post.content"></app-post>
            </ul>
        </div>
    </div>
</div>

listpost.component.ts

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

@Component({
  selector: 'app-listpost',
  templateUrl: './listpost.component.html',
  styleUrls: ['./listpost.component.scss'],
  changeDetection: ChangeDetectionStrategy.Default
})
export class ListpostComponent implements OnInit {

    private listPosts = [
        {
            title: 'Post example',
            content: 'Content example'
        }
    ];

    constructor() { }

    ngOnInit() {
    }

    addPostToList(newTitle, newContent){
        let newPost = {
            title: newTitle,
            content: newContent
        }

        this.listPosts.push(newPost);

        console.log("Added new post with title : \"" + newTitle + "\" and content : \"" + newContent + "\"");
        console.log(this.listPosts); //DEBUG
    }

    getListPosts(){
        return this.listPosts;
    }
}

The issue arises when clicking the button in app.component.html does not refresh the display in listpost.component.html, unlike when clicking the button within listpost.component.html.

Is there a way to specify the usage of the ListPostComponent instance received in the constructor of AppComponent within the HTML tag

<app-listpost></app-listpost>
?

Answer №1

To ensure efficient code organization, it is recommended to establish an injectable service that includes a method encapsulating the logic for adding a post to a list. Subsequently, create another function within your ListPostComponent component that invokes this service method and updates the listPosts accordingly. Finally, in your AppComponent, execute the function defined in your ListPostComponent.

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

Guide on retrieving documents from a collection in mongodb by utilizing the $nin operator

My user schema looks like this const userSchema= new mongoose.Schema({ Username:{ type:String, trim:true, required:true }, email:{ type:String, trim:true, required:true }, hashed_password:{ type:String, trim:t ...

Transmit the JSON Data file through an AJAX request

I am encountering an issue where the HttpPostedFileBase is null when trying to send an image file to a Controller. I have attempted entering image: image outside of JSON.stringify({}), but it did not work. Additionally, I tried changing the contentType f ...

Creating files using the constructor in Internet Explorer and Safari

Unfortunately, the File() constructor is not supported in IE and Safari. You can check on CanIUse for more information. I'm wondering if there's a workaround for this limitation in Angular/JavaScript? var file = new File(byteArrays, tempfilenam ...

Enhancing TypeScript modules - accessing the instance reference

While I have a good understanding of how module augmentation works, I am struggling to obtain the object reference in the new method's implementation. To provide an example, I aim to enhance the es2015 Map interface. In my code, I include: declare ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...

Navigating the parent-child hierarchy in Three.js

Two cubes were created with specific dimensions. The first cube had a width of 2083, height of 1987, and depth of 0. The second cube had a height of 40, width of 80, and depth of 0. The second cube was then positioned inside the first cube as its child wit ...

Execute the script repeatedly

(Since Stack snippet is temporarily down, I included a jsfiddle link): Visit this link for the code I've been struggling to get this script to work. Here's the simple Javascript code I have: $(document).ready(function() { showMessage(); s ...

The journey of a JavaScript file within an iframe devoid of any src attribute

Consider this scenario: In a folder labeled /jscript, there are two files named my_js_file1.js and my_js_file2.js. I also have an /index.html page structured like this: <html> <head> <script type='text/javascript' sr ...

Type with self-reference in index

Looking to create an interface with a mix of known and unknown members that should all have the same type. Here's what I have in mind: interface Foo { name?: string; [others: string]: Foo; } This setup would allow me to create something like ...

Troubleshooting problems with sending data in Jquery Ajax POST Request

I've spent a considerable amount of time searching for a solution to why my post request isn't sending its data to the server. Oddly enough, I can successfully send the request without any data and receive results from the server, but when attemp ...

Ways to extract precise information from MongoDB with the help of Mongoose?

I am facing an issue with retrieving and displaying data from MongoDB Atlas to use in my Discord bot replies. Below is the code I used to submit the data: const subregis = "!reg ign:"; client.on("message", msg => { if (msg.content.includes(subregis)) ...

Counter is effective for the initial post, yet it does not function properly for the subsequent post

Can anyone help with an issue I'm having with my JavaScript counter? It works for the first comment, but not the second one. This problem persists whether I use PHP or JavaScript. Below is the JavaScript code for the counter: var count = (function() ...

AngularJS is throwing an error claiming that the controller is not defined and is not a function

Struggling to create a basic angular application, every time I attempt it, I encounter this issue and can never find a solution. The content of App.js is as follows: angular.module('Euclid', ['ui.bootstrap', 'ngRo ...

Obtain every Scope within an AngularJS application

Is there a method to access all the Scopes within an AngularJS application? This would allow me to manage them at the same level and arrange them in a directive manner or order. Alternatively, is it possible to retrieve all the Scopes of the instances of ...

Emphasize links with larger background panels compared to the link object, minus any padding

http://jsbin.com/OkaC/1/edit HTML: <ul> <li> <a class='active' href='#'>Link</a></li> <li><a href='#'>Link</a></li> </ul> CSS: .active { bac ...

Accessing files for MongoDB cluster

My goal is to retrieve all the documents from a MongoDB cluster. Even though I have followed code examples from various online sources, I am encountering a minor issue. const MongoClient = require('mongodb'); const uri = "mongodb+srv://<user& ...

An issue arises when ReactRouter's useLocation is utilized, causing React to throw

https://i.sstatic.net/MtoLc.png Encountering an issue with useContext while utilizing the React Router useLocation hook. Attempting to retrieve information about the current page location using useLocation, but receiving the following error: useContext ...

Differences between typical functions and function variables in JavaScript

Can someone clarify the distinction between function MyFunc() { // code... } and var MyFunc = function() { // code... }; when it comes to JavaScript? ...

How can we prevent dispatching within a dispatch in React Flux?

It seems that I have come across a situation where I am struggling to avoid the dispatch-within-a-dispatch problem in Flux. While I have found similar questions addressing this issue, none of the solutions provided seem to be ideal, as they often involve ...

What are the best scenarios for implementing abstraction in Angular?

Throughout my experience, I have encountered Java EE, .Net, and various other enterprise application architectures. In each case, there was always an abstract upper class - like AbstractService for generalizing the service layer. However, in Angular, I ha ...