One place for hosting & domains

      Child

      How to Create a WooCommerce Child Theme


      Let’s say you have a WooCommerce store up and running.

      If you’re using the official Storefront theme, it might even look quite professional. However, you may still want to customize the appearance of your WooCommerce store to match your vision.

      The best solution is often to create a WooCommerce child theme. That’s because a child theme enables you to make changes to your original theme without editing it directly. It simplifies the process of customizing your store’s appearance and eliminates potential risks to your theme and store.

      In this article, we’ll look at how you can style your WooCommerce store using themes. Then, we’ll show you how to create your own child theme in just five steps. Let’s get started!

      A Quick Look at WooCommerce Themes

      With the launch of the WooCommerce plugin in 2011, WordPress became the most popular e-commerce platform. WooCommerce is currently used to power 25% of all online stores, making it 6% more popular than its closest competitor.

       

      One of the elements that has made WooCommerce so successful is how easy it is to create a unique store with minimal effort. However, this alone doesn’t explain the platform’s popularity.

      Another huge factor in WooCommerce’s success is the nearly infinite customization possibilities it offers. When combined with the right theme, you have access to a lot of design flexibility.

      WooCommerce is compatible with almost all WordPress themes. However, most of them will not be optimized to handle the unique features of the plugin.

      Fortunately, the Storefront theme is an excellent option. This is the official WooCommerce theme, built specifically to integrate with the plugin. It looks compelling right out of the box, with a simple and clean design that puts the focus on your products:

      the WooCommerce Storefront theme

      This bare-bones design also makes Storefront an ideal base for customization. This is where child themes come in handy, which we’ll look at next.

      Why You Might Want to Create a WooCommerce Child Theme

      If you’ve spent much time reading up on WordPress, you’ve probably come across child themes before.

      In short, a child theme starts life as a copy of another theme, which is known as the ‘parent theme’. You can then make changes to the child theme and test them out without editing the parent theme directly. This is important because altering the original theme can result in irreversible errors and even damage to your website.

      You might create a child theme because you want to use another theme as a basis, rather than having to build a new theme entirely from scratch. Alternatively, you may only want to make some minor changes to a theme’s branding or overall aesthetic. The sky really is the limit, depending on how much time you’re willing to devote to the project.

      When it comes to WooCommerce, most child themes are based on Storefront:

      Storefront child theme options in the official WooCommerce store

      You can download several child theme options from the official WooCommerce store or from other sites like ThemeForest. However, it’s possible that none of the existing child themes offered match your needs, or you may simply want to create a unique look. What’s more, you might not want to spend money on a premium theme if you feel you could do better yourself.

      In a post on the official WooCommerce blog, the plugin’s developers discuss the most common motivation behind using a child theme for your online store:

      “The aim with our own Storefront child themes is to deliver a store experience perfect for your own niche. After installing Galleria, and not touching any settings, you instantly have a store fit to sell high-end fashion items. With ProShop, you can rapidly set up a stylish sports store.”

      The actual process of creating a child theme is the same whether you’re making one specifically for WooCommerce or for a more general WordPress site. However, you will need to keep your store’s purpose in mind as you customize your child theme. An e-commerce site requires a different design philosophy than a blog, after all. Let’s see what this process looks like in practice!

      How to Create a WooCommerce Child Theme (In 5 Steps)

      Now, we’re going to walk you through how to create a WooCommerce child theme. In this example, we’ll create a basic theme that uses Storefront as its parent, although you can use any theme as a base.

      We’ll show you how the process works when starting from scratch. However, if you want to skip some of these steps and get straight to customizing your site, you can also download and install a sample Storefront child theme.

      Finally, we highly recommend creating a backup of your site before you proceed any further. This will keep your store safe if something breaks during the development process.

      It’s also smart to use a staging environment for creating and tweaking your child theme. Once you’ve taken these security precautions, you can proceed to the first step!

      Step 1: Make a Folder for Your WooCommerce Child Theme

      The first thing you’ll need to do is to create the folder that will contain your theme. If you’re adding the child theme directly to an existing site, the best way to do this is via SFTP. You can do this using a free application like FileZilla.

      Once you have the program up and running, log in to your site with your hosting credentials. Then, you’ll need to navigate to the wp-content/themes/ folder. This is where your site’s themes are installed.

      All you need to do is create a new folder within this one:

      the WordPress themes folder in FTP client

      When creating a child theme, it’s best to give it a name that reflects the parent. For example, we’re making a child theme for Storefront, so we’ll name our folder “storefront-child.”

      The first thing you’ll need to create and place in this folder is a simple text file called functions.php. This is an important core file that helps to dictate how your site looks and acts. However, most child themes can use the functions contained in the parent theme’s file and don’t need their own.

      For that reason, this file can be left blank for now. Simply create a text file with the name functions.php, and save it in your child theme’s folder:

      WordPress child theme location in FTP client

      Your theme is now almost ready to be activated and used. First, however, it will need a stylesheet.

      Step 2: Create Your Child Theme’s Stylesheet

      The next file you need to create is your theme’s Cascading Style Sheet (CSS). This file defines the styles that will be applied to your site’s pages and content. In other words, it enables you to specify the look of individual elements on your website. When people talk about updating styles, they’re usually referring to updating a site’s CSS file.

      Your parent theme will already contain a stylesheet, but a child theme’s CSS can be used to override those styles. We’ll look at how exactly this works later on.

      For now, you’ll just need to create the CSS file. To do this, once again add a text file to your wp-content/themes/storefront-child folder (or whatever name you used for your own child theme). This one should be called style.css:

      WordPress child theme location in FTP client

      You’ll also need to add some basic information. Copy and paste the following snippet into your new style.css file:

      /*
      Theme Name: Storefront Child
      Theme URI: http://example.com/storefront-child/
      Description: My first WooCommerce child theme
      Author: Your Name
      Author URI: http://example.com
      Version: 1.0.0
      License: GNU General Public License v2 or later
      License URI: http://www.gnu.org/licenses/gpl-2.0.html
      */

      These are the details about your theme that you’ll see when viewing it in a theme directory or in your WordPress dashboard. Feel free to replace the placeholder data with information more specific to you and your theme.

      Step 3: Configure the Child Theme to Inherit the Parent Theme’s Styles

      As we’ve already mentioned, you’ll want your child theme to use the parent theme’s default styles. However, you’ll also need to override the styles you want to change. This might sound complex — and CSS can indeed get tricky —  but at its core, the child will always use the parent theme’s styles unless it specifically contains a replacement.

      For example, let’s say your parent theme defines the style for h1 header elements as 20px and red. If the child’s style.css file does not contain an entry for H1 headers, then the parent style will be applied to all H1 content. However, if we were to add an H1 style to the child’s stylesheet that defined these headings as 18px and blue, it would override the parent’s directions.

      Adding this functionality to your child theme is actually very simple. All you need to do is to reference your parent theme in your child’s stylesheet.

      Simply add the following snippet after the information you pasted into the style.css file earlier:

      Template: storefront

      This code defines the parent theme and will ensure your child theme uses Storefront’s styles wherever you have not specified a replacement. If you’re creating a child for a different theme, you can simply use its folder’s name instead.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      Step 4: Activate the Child Theme

      At this point, your child theme is now technically ready. It’s configured to work on your site, so let’s activate it and see how it looks.

      Go to Appearance > Themes in your WordPress dashboard, and you’ll see your child theme already installed:

      activating your WooCommerce child theme in WordPress

      Select Activate to make it your site’s current theme. You can now preview it from the front end:

      editing your WooCommerce child theme

      As you can see, it looks exactly the same as the original theme right now. While the child theme is active, all it’s doing is pulling in the styles from your parent theme. To customize its appearance, you’ll need to get creative with your child theme’s stylesheet.

      Step 5: Add Styles to the Child Theme

      Finally, it’s time to start styling your child theme. Exactly how you do this is up to you, your creativity, and what you want your store to look like. However, let’s walk through an example of what you can do.

      To illustrate how editing your child theme works, we’ll change the look of our store’s buttons. At the moment, they appear gray with black text, but we could update this styling to make them stand out more:

      editing your WooCommerce child theme

      Open your child theme’s style.css file again, and add the following code after the last */ in the file’s header:

      a.button,
      button.button,
      input.button,
      #review_form #submit {
      background: pink;
      color: red;
      }

      If you save your file and view it on the front end now, you’ll see the change in action. The buttons will now be a vibrant pink with red text:

      editing your WooCommerce child theme

      You can also make changes to your theme’s template files. You’ll just need to copy the template file you want to alter, such as header.php, from your parent to your child theme folder.

      However, you’ll also need to make some changes to specify which function WordPress uses to reference the template files. This requires using the get_stylesheet_directory(); function instead of get_template_directory() to reference your templates.

      To learn more about how to do this, you can read about all the templates that WooCommerce uses.

      At this point, you have created a WooCommerce child theme! Of course, there’s plenty more you can do, but you now know how to start tinkering. We recommend you brush up on CSS to get the most out of your styling!

      Create a WooCommerce Child Theme

      WooCommerce makes it easy to create an online store, and you can even change its look using the Storefront theme or one of many custom themes.

      However, you don’t have to rely on the creativity of others. Creating your own WooCommerce child theme is not as difficult as you might think, and it gives you nearly total control over the look and functionality of your store.

      Happy selling!

      Your Store Deserves WooCommerce Hosting

      Sell anything, anywhere, anytime on the world’s biggest eCommerce platform.

      shared hosting



      Source link

      How to Create a WordPress Child Theme (Tutorial)


      In this article, we’re going to talk more about what WordPress child themes are and why you should use them. Then we’ll talk about some situations where it makes sense to create a child theme and teach you how to do it.

      One of the best things about using WordPress is its near-endless customization options. However, there are some protocols you should follow before you dive under the hood. Otherwise, your customizations may not work as intended.

      That’s where child themes come to the rescue. They’re a WordPress feature enabling you to customize your themes safely and keep all your tweaks organized. Once you learn how to use them, your life should get a lot easier, particularly if you spend a lot of time playing with your theme’s style and behavior.

      What is a WordPress Child Theme?

      A WordPress child theme works just the same as a regular one on the surface. Once activated, it’ll work just as any of your other themes would. The difference is, child themes have a ‘parent’ from which they inherit all their attributes.

      For example, imagine you’re using the Twenty Twenty-Two theme on your blog. You can create a child for it at any point, which would look and work just the same. However, you can customize every aspect of how a child theme works without affecting its parent. Here’s how that can work in your favor:

      • You can update your themes safely. When you update a theme, you also lose any changes you’ve made to its code in the process. However, if you’re using a child theme and you update its parent, you bypass this issue.
      • It’s easier to keep track of the changes you make to a theme. Many WordPress themes include dozens of files and hundreds of lines of code. That means any change to them — no matter how small — can be tricky because it’s easy to lose track of those tweaks. With a child theme, you can make changes to your heart’s content and still keep things tidy.

      Let’s summarize what we’ve learned thus far using an example.

      If you create a child theme for Twenty Twenty-Two, WordPress will recognize it as a different item. However, the child theme will inherit all of its parent’s styles and features. WordPress then loads any changes that override its default configuration. If so, it’ll render those instead of the default Twenty Twenty-Two theme files.

      It sounds tricky, but it’s simple once you learn how to create one and see it in action.

      When It Makes Sense to Use a WordPress Child Theme

      If you plan on making changes to your theme, you should create a child for it. However, if you’re completely satisfied with the way your theme works and looks, you can use it as is.

      Pro tip: You can also decide to use WordPress’ custom/additional CSS capability if only CSS changes are required. This is much simpler than creating a child theme and can be done directly from the Customizer.

      If you’re still on the fence about whether it’s a good idea to use a child theme or not, here are a few examples of situations where doing so makes sense:

      • If you’re going to make any changes — permanent or temporary — to your active theme’s functionality or style.
      • When using a theme that receives constant updates (which is a good thing!) and you don’t want to lose your customizations during the process.
      • To test changes you may want to implement on your active theme using a safe environment.

      Any of these scenarios are good reasons to use child themes day-to-day. However, if you’re going to create one mainly for test purposes, you may also want to look into setting up a staging website.

      How to Create a WordPress Child Theme (in 5 Steps)

      If this is your first time setting up a WordPress child theme, you should definitely back up your website. Don’t be scared — the process is very straightforward, but it always pays to err on the side of caution.

      Also, before we jump in, you should already know which theme you want to use as the parent in this scenario. If you’re just doing this for testing purposes, feel free to pick one of WordPress’ default themes for now.

      1. Create a Folder for Your Child Theme

      The first step is, of course, the simplest. Each theme you install on your website has its own folder within a dedicated themes directory on your server. To kick things off, we’re going to create a new subdirectory for your new child theme.

      There are plenty of ways to interact with your website’s file structure — such as through your panel — but we’re partial to Secure File Transfer Protocol (SFTP) due to its ease of use. To access your website via FTP, you’ll need a dedicated client. We recommend using FileZilla since it’s easy to pick up even for beginners, and it’s under constant development. If you’re not au fait with using FTP, you’ll also need to brush up on your skills before tackling these steps.

      Once installed, access your website’s directory using your SFTP credentials. This directory most often shows up as public_html but at DreamHost, the default is the domain you’ve added (example.com).

      Enter the directory and make your way to wp-content/themes/. Inside, you’ll find a unique folder for each of your WordPress themes.

      The Themes folder in wpcontent

      Now, right-click anywhere within the themes directory, pick the Create directory option, then set a name for your new folder:

      Creating a child theme folder

      Your child theme’s folder can have any name you want. However, for practical purposes, we recommend giving it a title you can easily recognize, such as twentytwentytwo-child (or something else, depending on what its parent theme is).

      Once you have a folder for your child theme ready to go, you’re ready to move on to step number two.

      2. Create a Theme Stylesheet

      As you may know, stylesheets are the CSS files that provide your pages with most of their visual flair. Each theme comes with its own unique stylesheet, and your child is no exception. Remember that by default your child theme will inherit all its parent’s styles. However, you can override those by adding new code to the style.css file you’re about to create.

      While your child theme’s style.css file will come in handy down the line, it also fulfills an important purpose right now. It simply tells WordPress “Hey, I’m a theme as well, load me alongside the rest!”

      For that to happen, you need to return to your child theme’s directory and access it. Right now, the folder should be empty. Right-click anywhere within and choose the Create new file option. When FileZilla prompts you to choose a name for it, type style.css and confirm your decision.

      Creating a style.css file

      Finally, we need to add a short snippet of code to that file. Right-click on it and choose View/Edit. This option will download a copy of the file to your computer and open it using your local editor. When the file is open, you’ll need to paste in the following text:

      /*
      Theme Name: Twenty Twenty-Two Child
      Theme URI: http://example.com/twenty-twenty-two-child/
      Description: Your first child theme!
      Author: John Doe
      Author URI: http://example.com
      Template: twentytwentytwo
      Version: 1.0.0
      License: GNU General Public License v2 or later
      License URI: http://www.gnu.org/licenses/gpl-2.0.html
      Tags: child theme
      Text Domain: twenty-twenty-two-child
      */

      At first glance, this seems like a lot of information, but for a child theme to work, there’s only one field you need to get right: Template. In the example above, you can see we used twentytwentytwo, which is the name of the Twenty Twenty-Two theme’s directory. If you’re using a different theme as a parent, you need to replace that value with the name of its folder (not the theme’s full name).

      You’ll also want to pick a title and description that makes sense for your child theme since you’ll see both within WordPress’ Theme tab. As for the rest of the fields, the values can be replaced with anything you like.

      Moving on, after you’ve set the correct Template value and tweaked the code, you can save the changes to your style.css file and close the text editor. Now, FileZilla will ask you if you want to replace the file on your server with the local copy you just modified. Say Yes, and access your WordPress dashboard. If you look at the Themes tab, you should see a new addition.

      The Theme’s tab in WordPress

      3. Configure Your Child Theme to Inherit Its Parent’s Style

      By now, you should have created a folder and style.css file for your new child theme. Within the latter, we included information designating it as a theme. The next step is to make sure your child theme inherits its parent’s style and features.

      To do this, we’re going to use a functions.php file, which enables you to instruct WordPress to add new features. Within that file, we’re going to add a script to “queue up” your parent theme’s stylesheet (not the one we just created). Afterward, your child theme will be ready for you to use.

      To start, return to your child theme’s directory. Inside, create a new file called functions.php, just as you did with style.css during step number two.

      Creating a functions.php file for a child theme

      Now open the file using FileZilla’s View/Edit option and paste the following code within:

      add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );
      function enqueue_parent_styles() {
      wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
      }

      In this case, there’s no need to replace any of the code’s values. The same code will work regardless of which parent theme you’re using since you already designated this using the style.css file.

      To make a long story short, that snippet of code tells WordPress it should load your parent theme’s stylesheet, which is the last piece of the puzzle you need for your child theme to work.

      Now save the changes to your functions.php file and close it. Make sure to agree when FileZilla asks you if you want to replace your website’s functions.php file, and that’s it! Now your child theme is ready for its grand debut.

      4. Activate Your New Child Theme

      To use your child theme, return to your WordPress dashboard and go to the Appearance > Themes tab. Inside, there should be one theme without a featured image — your child theme.

      Activating a child theme

      Click on the Activate button next to the theme’s name and open your website as you normally would. If you followed the previous three steps to the letter, your site should look exactly as it did before we got started.

      The Twenty Twenty-Two theme

      Feel free to take a quick look around just to triple check everything is working correctly. If the answer is “Yes” (which it should be), you’re ready to move on to the second part of this tutorial, where we’ll talk about how to use your new child theme.

      However, before that, let’s make one quick pit stop and add a featured image to your child theme.

      5. Add an Image to Your Child Theme

      Just so we’re clear — when we talk about a theme’s featured image, we’re referring to the graphic that shows up above its name within the Themes tab. Here are a few examples.

      A theme’s featured image

      Newly minted child themes don’t come with these images, so you need to provide one for WordPress to load it. Fortunately, this is a very simple process. All you have to do is add a PNG image called screenshot.png within your child theme’s directory.

      Adding a screenshot.png file to your child theme’s directory

      WordPress will display this image at a 387 x 290 resolution. However, you’ll probably want to save it using a higher dimension so it displays well on larger screens. In any case, you can use any image you want as your theme’s screenshot.

      A child theme with a featured image

      With that out of the way, your Themes tab should be looking fabulous once more, so it’s time to get back to business.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      How to Customize Your WordPress Child Theme (4 Tips)

      At this stage, you should have a fully working child theme on your hands. More importantly, you also have a firm understanding of how the entire process works and why each step in creating one is necessary. This means we can jump right into playing around with your child theme using the files you just created!

      1. Add Custom Styles

      As you already know, every WordPress child theme automatically inherits its parent’s styles. However, they also have their own stylesheet. Any customizations you add to your child theme’s style.css file will then override their parent’s styles if there’s any conflict between them.

      Tweaking your theme’s style using CSS is simple as long as you know what its elements are. Even if you don’t, you can easily find out using a web inspector, such as Chrome DevTools, which is included with your browser. Just right-click the element you want to alter and select the Inspect option.

      Inspecting an element in Google Chrome

      Now, the page’s source code will show up on a column to your right, including the specific class for the element you’re inspecting:

      Analyzing an element’s CSS class

      Armed with that information, you can access your child theme’s style.css file and add the necessary code to tweak it. You can then save the changes to your style.css file and you’re good to go. Return to your website’s front end to see what your theme looks like now.

      2. Learn to Override Your Parent Theme’s Files

      A minute ago, we talked about how your child theme’s style.css automatically override its parent theme’s code. The same holds true for any other file of which there are two between your parent theme and its child.

      Imagine, for example, you decide to create a child for the Twenty Twenty-Two theme. The parent, in this case, has a footer.php file within its theme folder:

      A theme’s footer.php file

      If you were to create a footer.php file within its child theme, WordPress would automatically load that one instead. The platform does this as long as both files share the same folder tree structure. In this case, since your parent theme’s footer.php file is located at the top of the twentytwentytwo directory, the same has to hold true for its counterpart.

      Adding a footer.php file to a child theme

      As long as both files share the same name, WordPress will do the rest. Using this trick, you’ll be able to alter any aspect of your theme’s functionality. Plus, if you ever break anything, you can simply delete the offending file from your child theme’s directory and start over.

      3. Create Custom Page Templates

      Whenever you create a new page in WordPress, you can choose which template to use alongside it. Some of the most common examples include full-width layouts or those with sidebars.

      Choosing a page template in WordPress

      You can add a new layout to any theme you want, although the process is a bit involved. If you want to try your hand at creating a new one, here’s a tutorial to get you started.

      4. Use Theme Hooks

      In WordPress, hooks are triggers that enable you to add custom code when something happens or tweak the way your files work. These are both things you can accomplish by modifying your files, but using hooks is much cleaner since they exist separately.

      Learning how to create hooks is a bit beyond the scope of this article, though.

      In short, you can add hooks to your child theme using its own functions.php file. This way, any modifications you make remain independent of its parent theme.

      Unlock the Benefits of WordPress Child Themes

      WordPress child themes can be intimidating at first. Creating one requires you to roll up your sleeves, but after you do it, you’ll realize the process isn’t that complicated. Plus, adding customizations to your child theme should provide you with a better understanding of how WordPress works, which can open a lot of doors. Who knows? At some point, you may even end up creating your own theme.

      Do More with DreamPress

      DreamPress Plus and Pro users get access to Jetpack Professional (and 200+ premium themes) at no added cost!

      Managed WordPress Hosting - DreamPress



      Source link

      3 Ways to Pass Async Data to Angular 2+ Child Components


      Let’s start with a common use case. You have some data you get from external source (e.g. by calling API). You want to display it on screen.

      However, instead of displaying it on the same component, you would like to pass the data to a child component to display.

      The child component might has some logic to pre-process the data before showing on screen.

      Our Example

      For example, you have a blogger component that will display blogger details and her posts. Blogger component will gets the list of posts from API.

      Instead of writing the logic of displaying the posts in the blogger component, you want to reuse the posts component that is created by your teammate, what you need to do is pass it the posts data.

      The posts component will then group the posts by category and display accordingly, like this:

      blogger and posts

      Isn’t That Easy?

      It might look easy at the first glance. Most of the time we will initiate all the process during our component initialization time – during ngOnInit life cycle hook (refer here for more details on component life cycle hook).

      In our case, you might think that we should run the post grouping logic during ngOnInit of the posts component.

      However, because the posts data is coming from server, when the blogger component passes the posts data to posts component, the posts component ngOnInit is already fired before the data get updated. Your post grouping logic will not be fired.

      How can we solve this? Let’s code!

      Our Post Interfaces and Data

      Let’s start with interfaces.

      // post.interface.ts
      
      // each post will have a title and category
      export interface Post {
          title: string;
          category: string;
      }
      
      // grouped posts by category
      export interface GroupPosts {
          category: string;
          posts: Post[];
      }
      

      Here is our mock posts data assets/mock-posts.json.

      
      [
          { "title": "Learn Angular", "type": "tech" },
          { "title": "Forrest Gump Reviews", "type": "movie" },
          { "title": "Yoga Meditation", "type": "lifestyle" },
          { "title": "What is Promises?", "type": "tech" },
          { "title": "Star Wars Reviews", "type": "movie" },
          { "title": "Diving in Komodo", "type": "lifestyle" }
      ]
      
      

      Blogger Component

      Let’s take a look at our blogger component.

      // blogger.component.ts
      
      import { Component, OnInit, Input } from '@angular/core';
      import { Http } from '@angular/http';
      import { Post } from './post.interface';
      
      @Component({
          selector: 'bloggers',
          template: `
              <h1>Posts by: {{ blogger }}</h1>
              <div>
                  <posts [data]="posts"></posts>
              </div>
          `
      })
      export class BloggerComponent implements OnInit {
      
          blogger="Jecelyn";
          posts: Post[];
      
          constructor(private _http: Http) { }
      
          ngOnInit() { 
              this.getPostsByBlogger()
                  .subscribe(x => this.posts = x);
          }
      
          getPostsByBlogger() {
              const url="assets/mock-posts.json";
              return this._http.get(url)
                  .map(x => x.json());
          }
      }
      

      We will get our mock posts data by issuing a HTTP GET call. Then, we assign the data to posts property. Subsequently, we bind posts to posts component in our view template.

      Please take note that, usually we will perform HTTP call in service. However, since it’s not the focus of this tutorial (to shorten the tutorial), we will do that it in the same component.

      Posts Component

      Next, let’s code out posts component.

      // posts.component.ts
      
      import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
      import { BehaviorSubject } from 'rxjs/BehaviorSubject';
      import { Post, GroupPosts } from './post.interface';
      
      @Component({
          selector: 'posts',
          template: `
          <div class="list-group">
              <div *ngFor="let group of groupPosts" class="list-group-item">
                  <h4>{{ group.category }}</h4>
                  <ul>
                      <li *ngFor="let post of group.posts">
                          {{ post.title }}
                      </li>
                  </ul>
              <div>
          </div>
          `
      })
      export class PostsComponent implements OnInit, OnChanges {
      
          @Input()
          data: Post[];
      
          groupPosts: GroupPosts[];
      
          ngOnInit() {
          }
      
          ngOnChanges(changes: SimpleChanges) {
          }
      
          groupByCategory(data: Post[]): GroupPosts[] {
              // our logic to group the posts by category
              if (!data) return;
      
              // find out all the unique categories
              const categories = new Set(data.map(x => x.category));
      
              // produce a list of category with its posts
              const result = Array.from(categories).map(x => ({
                  category: x,
                  posts: data.filter(post => post.category === x)
              }));
      
              return result;
          }
      }
      

      We have an input called data which will receive the posts data from parent component. In our case, blogger component will provide that.

      You can see that we implement two interfaces OnInit and OnChanges. These are the lifecycle hooks that Angular provide to us. We have not done anything in both ngOnInit and ngOnChanges just yet.

      The groupByCategory function is our core logic to group the posts by category. After the grouping, we will loop the result and display the grouped posts in our template.

      Remember to import these components in you module (e.g. app.module.ts) and add it under declarations.

      Save and run it. You will see a pretty empty page with the blogger name only. That’s because we have not code our solution yet.

      Solution 1: Use *ngIf

      Solution one is the easiest. Use *ngIf in blogger component to delay the initialization of posts components. We will bind the post component only if the posts variable has a value. Then, we are safe to run our grouping logic in posts component ngOnInit.

      Our blogger component:

      // blogger.component.ts
      
      ...
          template: `
              <h1>Posts by: {{ blogger }}</h1>
              <div *ngIf="posts">
                  <posts [data]="posts"></posts>
              </div>
          `
      ...
      

      Our posts component.

      // posts.component.ts
      
      ...
          ngOnInit() {
              // add this line here
              this.groupPosts = this.groupByCategory(this.data);
          }
      ...
      

      A few things to note:

      • Since the grouping logic runs in ngOnInit, that means it will run only once. If there’s any future updates on data (passed in from blogger component), it won’t trigger again.
      • Therefore, if someone change the posts: Post[] property in the blogger component to posts: Post[] = [], that means our grouping logic will be triggered once with empty array. When the real data kicks in, it won’t be triggered again.

      Solution 2: Use ngOnChanges

      ngOnChanges is a lifecycle hook that run whenever it detects changes to input properties. That means it’s guaranteed that everytime data input value changed, our grouping logic will be triggered if we put our code here.

      Please revert all the changes in previous solution

      Our blogger component, we don’t need *ngIf anymore.

      // blogger.component.ts
      
      ...
          template: `
              <h1>Posts by: {{ blogger }}</h1>
              <div>
                  <posts [data]="posts"></posts>
              </div>
          `
      ...
      

      Our posts component

      // posts.component.ts
      
      ...
          ngOnChanges(changes: SimpleChanges) {
              // only run when property "data" changed
              if (changes['data']) {
                  this.groupPosts = this.groupByCategory(this.data);
              }
          }
      ...
      

      Please notes that changes is a key value pair object. The key is the name of the input property, in our case it’s data. Whenever writing code in ngOnChanges, you may want to make sure that the logic run only when the target data changed, because you might have a few inputs.

      That’s why we run our grouping logic only if there are changes in data.

      One thing I don’t like about this solution is that we lose the strong typing and need to use magic string “data”. In case we change the property name data to something else, we need to remember to change this as well.

      Of course we can defined another interface for that, but that’s too much work.

      Solution 3: Use RxJs BehaviorSubject

      We can utilize RxJs BehaviorSubject to detect the changes. I suggest you take a look at the unit test of the official document here before we continue.

      Just assume that BehaviorSubject is like a property with get and set abilities, plus an extra feature; you can subscribe to it. So whenever there are changes on the property, we will be notified, and we can act on that. In our case, it would be triggering the grouping logic.

      Please revert all the changes in previous solution

      There are no changes in our blogger component:

      // blogger.component.ts
      
      ...
          template: `
              <h1>Posts by: {{ blogger }}</h1>
              <div>
                  <posts [data]="posts"></posts>
              </div>
          `
      ...
      

      Let’s update our post component to use BehaviorSubject.

      // posts.component.ts
      
      ...
          // initialize a private variable _data, it's a BehaviorSubject
          private _data = new BehaviorSubject<Post[]>([]);
      
          // change data to use getter and setter
          @Input()
          set data(value) {
              // set the latest value for _data BehaviorSubject
              this._data.next(value);
          };
      
          get data() {
              // get the latest value from _data BehaviorSubject
              return this._data.getValue();
          }
      
          ngOnInit() {
              // now we can subscribe to it, whenever input changes, 
              // we will run our grouping logic
              this._data
                  .subscribe(x => {
                      this.groupPosts = this.groupByCategory(this.data);
                  });
          }
      ...
      
      

      First of all, if you are not aware, Javacript supports getter and setter like C# and Java, check MDN for more info. In our case, we split the data to use getter and setter. Then, we have a private variable _data to hold the latest value.

      To set a value to BehaviorSubject, we use .next(theValue). To get the value, we use .getValue(), as simple as that.

      Then during component initialization, we subscribe to the _data, listen to the changes, and call our grouping logic whenever changes happens.

      Take a note for observable and subject, you need to unsubscribe to avoid performance issues and possible memory leaks. You can do it manually in ngOnDestroyor you can use some operator to instruct the observable and subject to unsubscribe itself once it meet certain criteria.

      In our case, we would like to unsubscribe once the groupPosts has value. We can add this line in our subscription to achieve that.

      // posts.component.ts
      
      ...
          ngOnInit() {
              this._data
                  // add this line
                  // listen to data as long as groupPosts is undefined or null
                  // Unsubscribe once groupPosts has value
                  .takeWhile(() => !this.groupPosts)
                  .subscribe(x => {
                      this.groupPosts = this.groupByCategory(this.data);
                  });
          }
      ...
      
      

      With this one line .takeWhile(() => !this.groupPosts), it will unsubscribe automatically once it’s done. There are other ways to unsubscribe automatically as well, e.g take, take Util, but that’s beyond this topic.

      By using BehaviorSubject, we get strong typing, get to control and listen to changes. The only downside would be you need to write more code.

      Which One Should I Use?

      The famous question comes with the famous answer: It depends.

      Use *ngIf if you are sure that your changes run only once, it’s very straightforward. Use ngOnChanges or BehaviorSubject if you want to listen to changes continuously or you want guarantee.

      That’s it. Happy Coding!



      Source link