I'm working with three components in my Angular application: app.component, post-create.component, and post-list.component. Let's take a look at the structure of these components:
<app-header></app-header>
<main>
<app-post-create (postCreated)="onAddedPost($event)" ></app-post-create>
<app-post-list [posts]="storedPosts" ></app-post-list>
</main>
The post-list.component.ts file contains code similar to this:
import { Component, Input } from '@angular/core';
import { Post } from '../post'
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css']
})
export class PostListComponent {
@Input() posts:Post[] = [];
}
The post-create.component.ts file includes the following code:
import { sharedStylesheetJitUrl } from '@angular/compiler';
import { Component, EventEmitter, Injectable, Output, OutputDecorator } from '@angular/core';
import { Post } from '../post'
@Component({
selector: 'app-post-create',
templateUrl: './post-create.component.html',
styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent {
enteredContent='';
enteredTitle='';
@Output() postCreated: EventEmitter<Post> = new EventEmitter<Post>();
onAddPost(){
const post={title:this.enteredTitle,content:this.enteredContent};
this.postCreated.emit(post);
}
}
Lastly, the app.component.ts file looks like this:
import { Component, Output,Input } from '@angular/core';
import { Post } from '../app/posts/post';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
storedPosts: Post[] = [];
onAddedPost(post:Post){
this.storedPosts.push(post);
}
}
If you're facing an issue where the newly added post is not showing up after pressing the add post button, make sure to check your template files for any errors or inconsistencies. For example, here is how the post.create.component.html should look:
<mat-card>
<mat-form-field>
<input matInput type="text" [(ngModel)]="enteredTitle">
</mat-form-field>
<mat-form-field>
<textarea matInput rows="6" [(ngModel)]="enteredContent"></textarea>
</mat-form-field>
<button mat-raised-button
(click)="onAddPost()">Save post!</button>
</mat-card>
Additionally, the post-list.component.html should be structured as follows:
<mat-accordion multi="true" *ngIf="posts.length>0" > ;
<mat-expansion-panel *ngFor="let post of posts">
<mat-expansion-panel-header>
{{post.title}}
</mat-expansion-panel-header>
{{post.content}}
</mat-expansion-panel>
</mat-accordion>
<p class="mat-body-1" *ngIf="posts.length <=0">no posts added yet</p>