Tuesday, 5 May 2020

Build Your Own Blog - Create the BlogPost Component

<< Create Your First Component                        Table of Contents                   Create the BlogArchive Component >>  

We will now create a component containing the content of a blog. It will look like below:



(If you're new here, I recommend visiting the Table of Contents)

Each blog post will contain:
  • Date
  • Title
  • Content as HTML capable of supporting images, code snippets and text
  • Posted by and at what time.
  • A border - green-ish with a drop shadow.
Let's get started!

1. Add a new component called 'blogpost' by running:

 ng generate component blogpost

2. Open blogpost.component.sass and add the following classes:








































The blog-post class defines the border of the component. We set the height:auto so that the components height will be defined based on it's content. However, we don't allow it to be smaller than 150px.

word-wrap: break-word
forces the text in the component to move to a new line once it reaches the edge of the components width.

3. Create a new folder called 'types' in src > app > types






















4. Create a TypeScript file called BlogPost and add the following:













This class is responsible for transferring all the data from to the template (DOM). Think of this class as a Data Transfer Object (DTO) or a binding between the TypeScript Controller (blogpost.component.ts) and the View/Template.

5. Open blogpost.component.ts and add the following:



Notice that we create an instance of the BlogPost class, injecting in test data we wish to be displayed in the component. Later, we will modify this class to connect it to our backend API for fetching real blog data.

6. Open blogpost.component.html and add the following html, using the classes we've just defined:



The BlogPost component is now complete.

In my next post, we will create the BlogArchive component.


<< Create Your First Component                        Table of Contents                   Create the BlogArchive Component >>   













No comments:

Post a Comment