Yet Another Angular Article, Part 2 : components creation

benjamin_richard_ee22ca92

Benjamin RICHARD

Posted on November 29, 2024

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

💖 💪 🙅 🚩
benjamin_richard_ee22ca92
Benjamin RICHARD

Posted on November 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related