This component will manage the state of the blog posts and handle events emitted by the child component.
import { Component } from '@angular/core'; @Component({ selector: 'app-blog', templateUrl: './blog.component.html', styleUrls: ['./blog.component.css'] }) export class BlogComponent { posts = [ { title: 'Post 1', content: 'This is the content of post 1' }, { title: 'Post 2', content: 'This is the content of post 2' } ]; addPost(post) { this.posts.push(post); } }
blog.component.html
<div class="blog"> <h1>Blog</h1> <app-blog-list [posts]="posts"></app-blog-list> <app-blog-form (newPost)="addPost($event)"></app-blog-form> </div>
This component will display the list of blog posts.
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-blog-list', templateUrl: './blog-list.component.html', styleUrls: ['./blog-list.component.css'] }) export class BlogListComponent { @Input() posts: { title: string, content: string }[]; }
blog-list.component.html
<div class="blog-list"> <div *ngFor="let post of posts" class="blog-post"> <h2>{{ post.title }}</h2> <p>{{ post.content }}</p> </div> </div>
This component will allow the user to add new blog posts.
import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-blog-form', templateUrl: './blog-form.component.html', styleUrls: ['./blog-form.component.css'] }) export class BlogFormComponent { title = ''; content = ''; @Output() newPost = new EventEmitter<{ title: string, content: string }>(); submitPost() { if (this.title && this.content) { this.newPost.emit({ title: this.title, content: this.content }); this.title = ''; this.content = ''; } } }
blog-form.component.html
Make sure to declare your components in your AppModule
.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { BlogComponent } from './blog/blog.component'; import { BlogListComponent } from './blog-list/blog-list.component'; import { BlogFormComponent } from './blog-form/blog-form.component'; @NgModule({ declarations: [ AppComponent, BlogComponent, BlogListComponent, BlogFormComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }