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>
?