PASSWORD RESET

Live24U News

Angular 6 Components Tutorial

311 0

Angular 6 Components Tutorial

A component in Angular 6 provides you with the basic building blocks of your Angular app. When we used the Angular CLI to generate our project, it created a single component.

When you use the CLI to generate components, it creates 4 files:

> src
  > app
    app.component.html
    app.component.scss (or .css)
    app.component.spec.ts
    app.component.ts
  • The HTML file is the HTML template associated with that component.
  • The SCSS or CSS is the associated CSS rulesets for that component (whatever is defined in the HTML file)
  • The .spec.ts file is for testing purposes.
  • The .ts file is the actual component file, and it’s where you will likely spend most of your time. It defines a number of things.

Open up the app.component.ts file:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  title = 'app';
}

At the top, we have our imports. You will import other components here, along with service files. We’ll do that a little later.

The @Component decorator is an object with associated property / value pairs that defines important stuff associated with this component. For instance, you will see selector: ‘app-root’ – This provides this component with a unique identifier that is used in other areas of the app. You can also see templateUrl and styleUrls, which tells Angular where this component’s HTML and CSS files are located. There are other properties that can be added here, such as animations, but we’ll get to that later.

Finally, we have the logic section of the component file. This is where properties (we see that title was defined by the CLI), dependency injection and methods are defined.

Now that you understand the very basics of a component, let’s create a few of our own!

In the console, run:

> ng generate component sidebar
CREATE src/app/sidebar/sidebar.component.html (26 bytes)
CREATE src/app/sidebar/sidebar.component.spec.ts (635 bytes)
CREATE src/app/sidebar/sidebar.component.ts (274 bytes)
CREATE src/app/sidebar/sidebar.component.scss (0 bytes)
UPDATE src/app/app.module.ts (479 bytes)

Here, we’ve told the CLI to generate a component with the name of sidebar. It outputs the 4 files it created, along with the app module file it updated!

Let’s generate a few more components. Run the following commands to generate 3 more components:

> ng g c posts
> ng g c users
> ng g c details

Now, you should have a total of 5 components, 4 of which we just created ourselves. Shortly, you’ll see how all of these start to work with each other and in relation to the app.

Leave A Reply

Your email address will not be published.