Enhancing a child module in Angular 5

Having trouble updating a child component in Angular 5, despite efforts.

The home component receives data through a service.

There is a function named getTopicToFilter which gets updated by another component successfully, providing the TopicId via an @Output EventEmitter.

The issue lies in articles not being updated in the child component.

export class HomeComponent implements OnInit {
    loading = true;

    topics: Observable<Topic[]>;
    posts: Observable<Post[]>;

    public constructor(
        private blogService: BlogService
    ) { }


    ngOnInit() {
        this.posts = this.blogService.getPostsByTopic().share()
        
        Observable.forkJoin([
            this.posts
        ]).subscribe(
            response => { },
            error => {
                console.log('An error occurred:', error);
            },
            () => {
                this.loading = false;
            });
    }

    getTopicToFilter(topicId) {
        this.posts = this.blogService.getPostsByTopic(topicId)
    }

}

Html for HomeComponent:

<app-posts [posts]="posts | async"></app-posts>

Lastly, the child PostsComponent;

export class PostsComponent{
    @Input() posts: Post[];

    ngOnChanges(changes: SimpleChanges) {
        if (changes['posts']) {
            // Need help as this always displays the original insights and not the filtered list
            console.log(this.posts)
        }
    }
}

Update - this is my BlogService

public getPostsByTopic(topicId = ""): Observable<Post[]> {
   return this.http.get<Post[]>(this.baseUrl + '/getPostsByTopic?TopicId=${topicId}', { headers });
}

Answer №1

class PostList {
  constructor() {
    this.posts = [];
  }

  updatePosts(newPosts) {
    for (let post of newPosts) {
      this.posts.push(post);
    }
    console.log(this.posts);
  }
}

Answer №2

Consider making a modification

transform class ArticleComponent

by adjusting it to

transform class ArticleComponent implements AfterContentChecked

Answer №3

The most effective method I have found is to utilize *ngIf within the child component, like so:

<child-component [posts]="data | async" *ngIf="dataIsReady" ></child-component>

Within your parent component, make sure to update the data in this way:

this.dataIsReady = false;
this.postService.getData().subscribe(
   (result: any) => {
     this.data = result;
     this.dataIsReady = true;
   }
);

*ngIf triggers a re-render of the child component. I trust you will find this approach beneficial.

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

Ways to display the ping of a game server on your screen

Is there a way to display the game server's ping on the screen like in the example below? this.tfEnter.text = ShowPing + " ms"; Sometimes the code snippets provided in examples may not function properly. Channel List Image: https://i.stack ...

Is it necessary to use an EventEmitter explicitly when performing two-way binding in Angular 2?

If I have a Kitchen class structured like this: @Component({ template: ` <kitchen [(kitchenLunch)]=lunch></kitchen> ` }) export class House { private lunch: Lunch; } The House component: Includes a sub-component Ki ...

The current version of NPM - typescript is 2.2.2, and we are unable to update it to 2.4.1 due to it being a symlink

While attempting to install TypeScript through NPM, I encountered the error below. Can you help me identify the issue? Command: npm install typescript Error: The installation of TypeScript failed because it requires an update from version 2.2.2 to 2.4. ...

Unlock the Potential: Empowering Users with Nativescript Firebase Sign

Recently, I embarked on the journey of developing apps using NativeScript and Angular. Looking for a reliable database source, I decided to go with Google Firebase. Successfully migrating my SQL data to the Firebase real-time database, I am now able to s ...

Issue with Angular not rendering data retrieved from HTTP response

In my Service script class, I have defined a HomeApiService with the following code: export class HomeApiService{ apiURL = 'http://localhost:8080/api'; constructor(private http: HttpClient) {} getProfileData():Observable<HomeModelInterface[ ...

What seems to be the issue with my @typescript-eslint/member-ordering settings?

I am encountering an issue where my lint commands are failing right away with the error message shown below: Configuration for rule "@typescript-eslint/member-ordering" is throwing an error: The value ["signature","public-static-field","pro ...

Can you identify the category of the new Set containing the elements 1, 2, and 3?

As a beginner in TypeScript, I'm currently exploring the appropriate type for JavaScript's new Set([1, 2, 3]), but my search has been unsuccessful so far. For instance: const objNums: {[key: string]: number} = {one: 1, two: 2, three: 3}; const a ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

Understanding the Usage of FormData in NextJS

I'm trying to read fetch's body contents. Here's the code I'm using: fetch('/api/foo', { method: 'POST', body: new FormData(formRef.current), }); https://i.sstatic.net/6YB1V.png Now I need to parse the body dat ...

propagate the amalgamation of tuples as an argument

I'm working with a function that returns a union type of tuples. I need to pass this return value to another function that can accept all its forms using the spread operator .... type TupleUnion = readonly [number, number] | readonly [number, number, ...

Verify registration by sending an email to an alternate email address through Angular Firebase

I have implemented email verification for users before registration. However, I would like to receive a verification email to my own email address in order to finalize the registration process. I want to be notified via email and only after my approval sho ...

Using Angular 2 to round a calculated number within HTML

In the HTML code, there is a calculated number associated with Component1. Component1 serves as a tab page within a Bootstrap tab panel. Below is the HTML code with the tab panel: <div id="minimal-tabs" style="padding:75px;padding-top:60 ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Having issues with JSON.stringify not properly handling every property within an object in Typescript

While using JSON.stringify in Typescript, I encountered an issue where not all properties of the outermost object were being stringified. Here is the code snippet that showcases the problem: class Criterion { '@CLASS' = 'xyz.abc.Criterio ...

Verify if a section of an arc intersects with a circular shape

I'm currently working on determining the intersection between an arc and a circle. I have successfully identified intersections when I treat the arc as a complete circle using the code snippet provided. However, I am facing difficulty in finding a so ...

Are there any means to automatically generate placeholder methods and properties for constructor dependencies in Angular?

constructor(private a:dependencyA,private b:dependencyB,private c:dependencyC){ } Here is an example of how dependencyA is structured: export class dependencyA { showPopup: boolean; defaultProperties = { showPopup: this.showPopup, }; priva ...

Ways to utilize array reduce for organizing information

Can someone please guide me on how to use the reduce array method to sort entries by date in the following data: const entries = [ {date: 'lu'}, {date: 'lu'}, {date: 'ma'}, {date: 'ma'} ] I would like the ou ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

Having trouble getting my .Net Core Application to connect with SQL Server in a Docker Container

Currently delving into Chapter 4 of the enlightening "Essential Angular for ASP.Net Core MVC" written by Adam Freeman. My focus is on executing the initial DB to operate against SQL Server in a Docker Container. Here is the original docker-compose.yml fil ...

An error callback is triggered when the HttpClient delete function encounters an issue, despite receiving a successful

My attempt to remove a basic student object using its ID is functioning correctly. However, instead of displaying the success message, it appears as an error message. Java backend code -> Controller code: @DeleteMapping("/student/{$id}") ...