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! 🎉
In Angular, an Array is a collection of values, ordered and changeable. Arrays are used to store multiple values of the same data type.
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 is quite straightforward. You can create an empty array using the Array constructor or initialize it with values directly.
let numbers: number[] = []; // empty array
let numbers = [1, 2, 3]; // initialized arrayTo 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.
let fruits: string[] = ['Apple', 'Banana', 'Orange'];
console.log(fruits[0]); // Output: AppleTo manipulate array elements, you can use methods such as push, pop, shift, unshift, splice, sort, and reverse.
You can iterate through an array using a for loop or forEach function.
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);
});Let's put our knowledge into practice by building a simple To-Do List App.
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.
What is an Array in Angular?
What is the output of `console.log(fruits[0])` when `fruits` is defined as `let fruits: string[] = ['Apple', 'Banana', 'Orange']`?
How can you add a new item to an array using Angular?