3.4: Add Register and Home Components

First, let's generate the HomeComponent

ng g c home --no-spec

Inside of our HomeComponent, we'll create RegisterComponent

ng g c home/register --no-spec

HomeComponent

Inside of the home.component.html file remove the default and add the following:

<div class="home-container">
  <h1>
    Connect with other developers!
  </h1>
  <p class="lead">Come on in! All you have to do is sign up!</p>
  <div class="text-center">
    <button class="btn btn-primary btn-lg">Register</button>
    <button class="btn btn-info btn-lg">Learn More</button>
  </div>
</div>

Add the following styles to home.component.scss:

.home-container, .container {
    text-align: center;
    margin-top: 4%;
}

.container {
    width: 25%;
}

Next, inside of app.component.html, remove the default and add the HomeComponent:

Great! It's starting to look like a site!

RegisterComponent

Inside of register.component.html, add this layout with a template form ready to be implemented:

Next, inside of our register.component.ts file, we'll add some functionality to test that it's working:

Adding the Register Component to the Home Component

Inside the home.component.html file, we'll add the RegisterComponent below the other <div>:

Toggle Between Home and Register Component

Still in the home.component.html file, add an ngIf directive to the container holding the RegisterComponent:

And add a click event to the Register button:

Finally, add the registerToggle() method and a registerMode property to the component .ts file:

Now, we can show the RegisterComponent when a user clicks the button.

Pretty good. But, we'd like the cancel button to work and hide the welcome message.

The RegisterComponent is a child of the HomeComponent - so, we'll have to pass data around in order to toggle the registerMode property from the child.

Enabling the Cancel Button

We need to pass data from a child to a parent component. In order to do this we use an Output property with an EventEmitter.

In your register.component.ts file add this property and "emit" the event in the cancel() method:

In order to receive the data in our parent controller, we need to have a selector in the parent template file. This selector will call a method with the event being passed into it.

In home.component.html add the selector to the <app-register> directive:

Now, in the home.component.ts file, we'll create the cancelRegisterMode() method:

And, finally - we'll add an ngIf to the <div></div> with the home-container class in our home.component.html file:

Great! It should be working now. Make sure the Angular server is running - open the browser, and test it out!

CHALLENGE

Try to implement registering through the Angular app on your own before proceeding to the next step.

Last updated