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 :
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'; }
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 />
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 }
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
The above is the detailed content of Yet Another Angular Article, Part components creation. For more information, please follow other related articles on the PHP Chinese website!