Angular - 2-11 Exercice 1
It is time to put into practice what we have learned about components. In this exercise you will create, register, use and style your own components and see how an Angular application is composed of building blocks. Pause the video, take the time to work through it, then come back to compare with the proposed solution.
The first task is to create two new components - one by hand and one with the Angular CLI. We start manually: create a folder named warning-alert and a file warning-alert.component.ts inside it. In that file, export a class WarningAlertComponent and decorate it with @Component imported from @angular/core. The decorator must declare at least a selector (app-warning-alert) and a template. Here we will use an inline template with a paragraph that reads "Warning! you're in danger". The second component is generated with the CLI: ng generate component success-alert (or the shortcut ng g c success-alert). We delete the spec file we do not need, and inside the generated HTML file we display "Success! It is my success message".
Wire the components into the app
- Add
<app-warning-alert>and<app-success-alert>inapp.component.html, separated by an<hr>. SuccessAlertComponentwas registered automatically by the CLI. The manualWarningAlertComponentmust be imported and added to thedeclarationsarray ofAppModule.
If you skip the registration step you will see an error in the console: "app-warning-alert is not a known element". Once the import is added, the application displays both alerts. The final step is to style them. For the warning alert we use inline styles inside the decorator (styles: ['p { padding: 20px; background: lightpink; border: 1px solid red; }']). For the success alert we use the external CSS file already referenced by the CLI and pick a light green background with a green border. We end up with two boxes, one red and one green, each rendered by its own component. This exercise was meant to make you comfortable with creating, using and styling components. We will go deeper into Angular fundamentals in the next lessons.