Angular Tutorial: Bootstrap Array 🎯

beginner
13 min

Angular Tutorial: Bootstrap Array 🎯

Welcome to the Angular Tutorial series! Today, we're diving into Bootstrapping Arrays, a fundamental concept that will help you build dynamic and interactive applications. Let's get started! 🎉

What is an Array in Angular? 📝

In Angular, an Array is a collection of values, ordered and changeable. Arrays are used to store multiple values of the same data type.

typescript
let fruits: string[] = ['Apple', 'Banana', 'Orange'];

In the example above, we've created an array called fruits with three elements. The string[] part indicates that the array stores strings.

Creating an Array in Angular 💡

Creating an array in Angular is quite straightforward. You can create an empty array using the Array constructor or initialize it with values directly.

typescript
let numbers: number[] = []; // empty array let numbers = [1, 2, 3]; // initialized array

Accessing and Manipulating Array Elements 💡

To access an element in an array, you can use its index. In JavaScript, arrays are zero-indexed, meaning the first element has an index of 0.

typescript
let fruits: string[] = ['Apple', 'Banana', 'Orange']; console.log(fruits[0]); // Output: Apple

To manipulate array elements, you can use methods such as push, pop, shift, unshift, splice, sort, and reverse.

Iterating Through an Array 💡

You can iterate through an array using a for loop or forEach function.

typescript
let fruits: string[] = ['Apple', 'Banana', 'Orange']; // for loop for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } // forEach fruits.forEach((fruit) => { console.log(fruit); });

Example: A Simple To-Do List App 💡

Let's put our knowledge into practice by building a simple To-Do List App.

typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-todo', template: ` <ul> <li *ngFor="let todo of todos">{{todo}}</li> </ul> <input type="text" [(ngModel)]="newTodo" (keyup.enter)="addTodo()" placeholder="Add a new task" /> `, }) export class ToDoComponent { todos: string[] = []; newTodo: string = ''; addTodo() { if (this.newTodo.trim()) { this.todos.push(this.newTodo); this.newTodo = ''; } } }

In this example, we've created a ToDoComponent that displays a list of todos and allows adding new todos. The *ngFor directive is used to iterate through the todos array.

Quiz 📝

Quick Quiz
Question 1 of 1

What is an Array in Angular?

Quick Quiz
Question 1 of 1

What is the output of `console.log(fruits[0])` when `fruits` is defined as `let fruits: string[] = ['Apple', 'Banana', 'Orange']`?

Quick Quiz
Question 1 of 1

How can you add a new item to an array using Angular?