DEV Community

Benjamin RICHARD
Benjamin RICHARD

Posted on

Yet Another Angular Article, Part 2 : components creation

Image description

In the previous article, i just talked about project creation. I mean, the main project, not sub-projects. Those one will be the subject of a future article.

Today is related to component creation. And like project creation, the Angular CLI is your best friend. So go an with :

 
ng generate component hello-world

It run the code generation in the folder my-new-project/src/app/hello-world with 4 files :

  • hello-world.component.html : the template
  • hello-world.component.scss : the styles, in scss format since this is my choice at the project creation prompt
  • hello-world.component.spec.ts : the test file
  • hello-world.component.ts : the component

Now run ng serve and open the browser to localhost:4200 to see the result
Hey, but the component is not rendered ! Why ?
Because we didn't use it :-)

Now open the root component 'app.component.ts' and add HelloWorlComponent in 'imports' section :

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { HelloWorldComponent } from './hello-world/hello-world.component';
@Component({
 selector: 'app-root',
 imports: [RouterOutlet, HelloWorldComponent],
 templateUrl: './app.component.html',
 styleUrl: './app.component.scss',
})
export class AppComponent {
 title = 'angular-tutorial';
}
Enter fullscreen mode Exit fullscreen mode

The component is now available in AppComponent, and we can use it. Just edit the hello-world.component.html file and replace all the code by this :

<app-hello-world></app-hello-world>
<router-outlet />
Enter fullscreen mode Exit fullscreen mode

Forget router-outlet for instance since we didn't prevent the installation of Angular Router on project creation (if you don't want routing you can do this : ng new my-new-project --routing=false )

The default selector prefix is 'app', that's why the selector of the component is 'app-hello-world'

Check the browser and you will see the default content of your component.

You can customize the css by adding this to hello-world.component.scss :

:host {
 color: blueviolet
}
Enter fullscreen mode Exit fullscreen mode

Check the browser and you will see the new color of the text. The :host selector is related to the current hello-world component.

So now, you know how to generate a simple component

Have a nice day 🌞

[original post] https://rebolon.medium.com/yet-another-angular-article-part-2-components-creation-550c14b991a2

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay