Welcome to the third lesson in our Angular series! Today, we'll dive into the world of buttons and icons, essential components for user-friendly web applications.
Buttons are interactive elements that trigger actions when clicked. Let's create a simple Angular button:
<!-- app.component.html -->
<button (click)="onClickButton()">Click Me!</button>// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'My Angular App';
onClickButton() {
alert('Button clicked!');
}
}In the code above, we've created a button that triggers an alert when clicked. The (click) directive binds the button click event to the onClickButton() function in our component.
š Note: Angular uses TypeScript, a typed superset of JavaScript. You'll encounter more TypeScript in the upcoming sections.
Icons are a great way to enhance the visual appeal of your application. Angular provides various icon libraries, but today, we'll use the popular Font Awesome library.
First, let's install Font Awesome:
npm install @fortawesome/fontawesome-free @fortawesome/fontawesome-free-solidNow, include the Font Awesome styles in your index.html file:
<!-- index.html -->
<head>
...
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha384-wESLQ85D6gbsF459vf1CiU7FhCk3Jie1bt9ttokMinn5vmziws5QqroZs5NE" crossorigin="anonymous">
...
</head>Now, let's create an icon:
<!-- app.component.html -->
<i class="fas fa-bell"></i>In the code above, fas is the Font Awesome solid icon set, and fa-bell is the specific icon we're using.
For more advanced buttons, consider using Angular Material. It provides pre-built buttons with various styles and states.
First, install Angular Material:
ng add @angular/materialNow, include the Material styles in your index.html file:
<!-- index.html -->
<head>
...
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@angular/material@11.2.9/angular-material.min.css">
...
</head>Now, let's create a Material button:
<!-- app.component.html -->
<button mat-raised-button color="primary">Raised Button</button>In the code above, we've created a raised button with a primary color. The mat-raised-button directive binds the button to Angular Material's button component.
What is the purpose of the `(click)` directive in Angular?
That's it for today! In the next lesson, we'll explore more Angular components and directives. Keep coding! š