Angular

Fundamentals of Angular Directives - Component Directives

PRO
Outline

Directives with a Template

So far we have learned about two types of directives in Angular:

  1. Attribute Directives
  2. Structural Directies

If you recall, attribute directive are applied to a host element and enhance or modify the behavior or appearance of the element. And, structural directives enables us to efficiently create, remove and modify elements. Angular ships with three very powerful built-in directives, but we can also use the APIs provided by Angular to build our own structural directives.

Components = Directive + Template

Components are directives that include a template that is rendered in the place of the component. Components inherit all of the functionality and usability of directives plus a provided template. Angular uses a HTML-like template syntax that enables web developers to get started quickly with Angular. Templates can also be styled using vanilla CSS, Scss or LESS. Simply modify the extension of the file and Angular will compile the Scss or LESS.

We'll specify the template and styles using the @Component() decorator's metadata. For example, we can specify the template and CSS inline in the metadata:

@Component({
  selector: 'app-hello-world',
    template: `<h1>Hello, World!</h1>`,
    styles: [`h1 { font-weight: bold; }`],
})
export class HelloWorldComponent { }

Note that we are still specifying a selector. In this case the value is an element selector that matches an HTML element <app-hello-world>. We are also specify the template and styles properties. The styles property is an array of strings that contain CSS that is applied to the template.

We can also specify the template and style as URLs to external files:

@Component({
  selector: 'app-hello-world',
    templateURL: './hello-world.component.html',
    styleUrls: ['./hello-world.component.scss'],
})
export class HelloWorldComponent { }

We've simply swapped out the template property for the templateUrl property whose value is a relative path to the template file. And, we've removed the styles property for the styleUrls property whose value is the relative path to the styles file. In this example I'm referencing a Scss file, but you can use vanilla CSS as well as LESS.

 

I finished! On to the next chapter