ACTIVITY 8: Angular Components | Aligan, Rhed N.

ACTIVITY 8: Angular Components | Aligan, Rhed N.

Goal:

Create 50 Angular components, each with different functionality, based on the provided list and your own examples. Ensure all components are well organized and navigable from the main app component.

Instructions:

  1. Create 50 Components:

    • Implement 40 components from the provided instructions.

    • Create 10 additional components based on your own unique ideas.

    • In the app.component, add a header or navbar that includes links to all 50 components. This will allow users to easily navigate between them.

    • Note: Focus on using only HTML and TypeScript. For now, avoid using any CSS or external designs. The purpose is to practice functionality, not design.

  2. Commit and Push to GitHub:

    • For each component, create a separate commit with the following format:

      Example commit message: #1displayhelloworld

    • Ensure there are 50 commits in total, each corresponding to a different component.

    • Push the entire project to a GitHub repository.

  3. Documentation on Hashnode:

    • Write a short blog post on Hashnode explaining the project and components you built.

    • Include code snippets where necessary and explain the functionality of the components briefly.

    • Provide the link to your GitHub repository in the post so that others can access your code.

  4. Share on Portal:

    • Once you’ve completed the Hashnode documentation, share the link to your post on our portal.

Important Notes:

  • This is a practice activity to help you master Angular.

  • You must not use AI to generate any of the code. However, you are free to search for solutions on platforms like Google if needed.

  • Focus on functionality first and do not use CSS or external design tools. Stick to HTML and TypeScript only.

  • You are allowed to use AI tools only for writing documentation, like the Hashnode blog post.

Good luck, and have fun mastering Angular!

#1 component name: displayhelloworld

Display the text "Hello World" on the screen using a variable from the TypeScript file.

import { Component } from '@angular/core';

@Component({
  selector: 'app-displayhelloworld',
  templateUrl: './displayhelloworld.component.html',
  styleUrl: './displayhelloworld.component.css'
})
export class DisplayhelloworldComponent {
    hellomessage: string = 'Hello World'; // the hellomessage hold the value which is Hello World
}

The code snippets code above shows the displayhelloworld.components.ts.

the hellomessage hold the value of ‘Hello World’.

<p>{{ hellomessage }}</p>

In our displayhelloworld.components.html using 2 curly braces can be able to access the properties named “hellomessage”

OUTPUT:

#2 component name: showhellobutton

Create a button, and when the user clicks the button, "Hello World" is displayed on the screen.

In the code snippets above with given file name above code shows using *ngIf where in it use to the boolean behavior to trigger.

Additionally, the showMessage use for boolean condition where in the default is false. The text will display once the showMessage is become true by clicking button.

OUTPUT:

#3 component name: displayname

User inputs their name, and when the button is clicked, their name is displayed on the screen.

In code snippet below with given file name also in the image shows that user and TriggerDisplay we use as a properties to hold and trigger the button to display the name of user.

Additionally, our html includes of button where in encapsulate our function name showName and use if *ngIf to display all input of user in textbox. We access the input user by properties of TriggerDisplay.

OUTPUT:

#4 component name: counter

Create a counter that increases by 1 when the user clicks a button.

In image above with given filename, It shows the count as properties provide a default value of 0.

use function named incrementclick use to navigate the numbers based on click of button.

Additionally, our html has a button to trigger the function incrementclick to increase the number.

span tags to display only the default value which is 0.

OUTPUT:

#5 component name: simpleform

Create a form with text inputs and a submit button, display the submitted input data.

In code snippets with filename given, the name and email properties has not undefined but null since it’s a form. we use function name Submitname and copy the input into the display section.

Additionally, in our html, we use a form section with constraints of email and name so it can’t be process when one of them are empty. *ngIf use to display all input in a display section.

OUTPUT:

#6 component name: userage

Input user’s birth year, and when the button is clicked, display their age.

In the code snippets above given the file name, it shows the two properties, the birthyear and age that hold the input and display after calculation.

In function named calculate with a currentYear will minus input birth year.

Additionally, our html is use input and label tags and using ngModel to override the birthyear.

using *ngIf to display result what numerical user’s input after operation.

OUTPUT:

#7 component name: usergreeting

User inputs their name, and when clicked, display a personalized greeting.

In the code snippets given the file name shows that we user a user and greets for hold the value of input users’ data and how it be greeted as a whole sentence. Below is the function that will be trigger with button.

Additionally, in our html use ngIf to include all sentence for display. asterisks * use as include all data.

OUTPUT:

#8 component name: calculator

Create a simple calculator with add, subtract, multiply, and divide functionalities.

In the code snippets given with file name in the image shows typescript all function including addition, subtraction, multiplication, and division with input of 2 numbers. If the 2 numbers not visible by zero, it shows a error message.

Additionally, in our html shows different button with a different behavior how operation of 2 number of user's input.

OUTPUT (ADDITION) :

OUTPUT (SUBTRACTION) :

OUTPUT (MULTIPLICATION):

OUTPUT (DIVISION):

#9 component name: textlength

Input a string, and when the button is clicked, display the length of the string.

In the code snippets in textlength with provided file name in the image shoes how calculate the characters of what input users in text box. textlength property holds how many characters in the input data, while inputText use to determine the input is string.

Additionally, our html shows and use of *ngIf so all the user’s input in the text box shows the number of characters.

OUTPUT:

#10 component name: currencyconverter

Input a value in one currency, convert it to another currency on button click (1 dollar = 56 Php).

In our code snippets given the file name in the image shows conversion of Dollar to Pesos.

In addition, it shows our html input of dollar and convert it when the buttons clicked. Using *ngIf to have conversion and targeting the property of Pesos that only can able to input only numbers since we have number:1.2-2. its contraints only can input a numerical.

#11 component name: evenoddchecker

Input a number and check if it is even or odd.

import { Component } from '@angular/core';

@Component({
  selector: 'app-evenoddchecker',
  templateUrl: './evenoddchecker.component.html',
  styleUrl: './evenoddchecker.component.css'
})
export class EvenoddcheckerComponent {
  inputNumber: number | null = null; // for input number property
  result: string = ''; // identify result if odd or even

  // Function with name Checking
  Checking() {
    if (this.inputNumber === null) {
      this.result = 'Please enter a number';
    } else if (this.inputNumber % 2 === 0) {
      this.result = 'The number is even';
    } else {
      this.result = 'The number is odd';
    }
  }
}

In this code snippet above shows the function name “Checking”. we access the property of inputNumber in function by using “this.” result property use to hold the result of function.


<label for="inputNumber">Enter a number:</label><br>
<input type="number" id="inputNumber" [(ngModel)]="inputNumber" placeholder="Enter a number" /><br>

<button (click)="Checking()">Even or Odd</button>


<p>{{ result }}</p>

In addition, ngModel use for the input user wherein in trigger when the button clicks.

OUTPUT:

#12 component name: wordreverser

Input a word, and when the button is clicked, display the word reversed.

import { Component } from '@angular/core';

@Component({
  selector: 'app-wordreverser',
  templateUrl: './wordreverser.component.html',
  styleUrl: './wordreverser.component.css'
})
export class WordreverserComponent {
  inputWord: string = ''; 
  reversedWord: string = ''; 


  reverseWord() {
    this.reversedWord = this.inputWord.split('').reverse().join('');
  }
}
  • Imports: It imports the Component decorator from Angular's core library.

  • Component Decorator: The @Component decorator defines the component's metadata:

    • selector: Defines the component's HTML tag as <app-wordreverser>.

    • templateUrl: Links to the HTML file for the component (wordreverser.component.html).

    • styleUrl: Links to the CSS file for styling (wordreverser.component.css).

  • Class: The WordreverserComponent class contains:

    • inputWord: A string variable to hold the user's input.

    • reversedWord: A string variable to hold the reversed version of inputWord.

  • reverseWord Method: A function that reverses the inputWord by splitting it into an array of characters, reversing that array, and then joining the characters back into a string.

<!-- Input field for the word to be reversed -->
<label for="inputWord">Enter a word:</label><br>
<input type="text" id="inputWord" [(ngModel)]="inputWord" placeholder="Enter a word" /><br>

<!-- Button to trigger the word reversal -->
<button (click)="reverseWord()">Reverse Word</button>

<!-- Display the reversed word -->
<p *ngIf="reversedWord">Reversed Word: {{ reversedWord }}</p>

This HTML code is part of an Angular component that provides a simple user interface for reversing words. It includes an input field where users can enter a word, a button that triggers the reversal action, and a paragraph that displays the reversed word when available. The [(ngModel)] directive enables two-way data binding between the input field and the component’s property, while the *ngIf directive ensures the reversed word is only shown when it's not empty. The button’s click event calls the reverseWord() method to perform the reversal operation.

OUTPUT:

#13 component name: showdate

Create a button that shows the current date and time when clicked.

import { Component } from '@angular/core';

@Component({
  selector: 'app-showdate',
  templateUrl: './showdate.component.html',
  styleUrl: './showdate.component.css'
})
export class ShowdateComponent {
  currentDate: string | null = null; 


  showCurrentDate() {
    const now = new Date();
    this.currentDate = now.toLocaleString();
  }
}

This code creates an Angular component named ShowdateComponent that displays the current date and time. It imports the Component decorator from Angular’s core library. The @Component decorator specifies the component's selector (<app-showdate>), the HTML template (showdate.component.html), and the CSS file (showdate.component.css). The class contains a property currentDate initialized to null to store the current date and time as a string. The showCurrentDate() method, when called, gets the current date and time using new Date() and formats it to a readable string using toLocaleString(), updating the currentDate property.


<button (click)="showCurrentDate()">Show Current Date and Time</button>

<p *ngIf="currentDate">Current Date and Time: {{ currentDate }}</p>

This HTML code features a button and a paragraph used within the ShowdateComponent. The button element has a click event bound to the showCurrentDate() method, which, when triggered, displays the current date and time. The paragraph element utilizes Angular’s *ngIf directive to conditionally display the formatted date and time stored in the currentDate property of the component. This paragraph only appears when currentDate is not null, showing the current date and time in a readable format.

#14 component name: showusername

User inputs their username, and on clicking a button, their username is displayed on the screen.

import { Component } from '@angular/core';

@Component({
  selector: 'app-showusername',
  templateUrl: './showusername.component.html',
  styleUrl: './showusername.component.css'
})
export class ShowusernameComponent {
  username: string = ''; 
  displayedUsername: string | null = null; 


  showUsername() {
    this.displayedUsername = this.username;
  }
}

This Angular code sets up a component named ShowusernameComponent that displays a username entered by the user. It imports the Component decorator from Angular’s core module. The @Component decorator specifies the selector (<app-showusername>), the template URL (showusername.component.html), and the stylesheet (showusername.component.css). Inside the component class, there are two properties: username, which stores the input username, and displayedUsername, which is initially set to null. The showUsername() method assigns the value of username to displayedUsername, allowing the inputted username to be displayed when the method is triggered.

<br>
<label for="username">Enter your username:</label><br>
<input type="text" id="username" [(ngModel)]="username" placeholder="Enter your username" /><br>

<button (click)="showUsername()">Show Username</button><br>

<p *ngIf="displayedUsername">The Username: {{ displayedUsername }}</p>

This HTML code provides an interface for the ShowusernameComponent. It includes a label and an input field where users can enter their username, with the input field bound to the username property using Angular’s [(ngModel)] directive for two-way data binding. A button is provided to trigger the showUsername() method, which assigns the inputted username to displayedUsername. The paragraph element, using the *ngIf directive, conditionally displays the username when displayedUsername is not null, showing the entered username to the user.

OUTPUT:

#15 component name: multiplicationtable

Input a number and generate its multiplication table.

import { Component } from '@angular/core';

@Component({
  selector: 'app-multiplicationtable',
  templateUrl: './multiplicationtable.component.html',
  styleUrl: './multiplicationtable.component.css'
})
export class MultiplicationtableComponent {
  number: number = 0;
  table: number[] = [];

  generateTable() {
    this.table = [];
    for (let i = 1; i <= 10; i++) {
      this.table.push(this.number * i);
    }
  }
}

This code defines two properties within an Angular component: number, initialized to 0, and table, which is an array of numbers. The generateTable() method populates the table array with the multiplication results of number multiplied by integers from 1 to 10. It first clears the table array and then uses a for loop to calculate each product, pushing the results into the table array. This allows for the dynamic generation of a multiplication table whenever the method is called.

<div><br>
    <h2>Multiplication Table Generator</h2><br>
    <input type="number" [(ngModel)]="number" placeholder="Enter a number" /><br>
    <button (click)="generateTable()">Generate Table</button>

    <div *ngIf="table.length">
      <h3>Multiplication Table for {{ number }}</h3>
      <ul>
        <li *ngFor="let value of table">{{ number }} x {{ (table.indexOf(value) + 1) }} = {{ value }}</li>
      </ul>
    </div>
  </div>

This HTML code creates a simple interface for the Multiplication Table Generator. It includes a header, an input field for entering a number, and a button to trigger the table generation. The input field is bound to the number property using Angular's [(ngModel)] for two-way data binding. When the button is clicked, it calls the generateTable() method. If the table array has values, a section displays the multiplication table, showing the header for the specific number and listing the results in an unordered list. Each list item is generated using *ngFor, displaying the multiplication operation and its result, dynamically calculating the multiplier using the index of the value in the table array.

OUTPUT:

#16 component name: simplelogin

Create a simple login form with email and password fields.

#17 component name: fahrenheittocelsius

Convert temperature from Fahrenheit to Celsius when the user inputs a value.

import { Component } from '@angular/core';

@Component({
  selector: 'app-simplelogin',
  templateUrl: './simplelogin.component.html',
  styleUrl: './simplelogin.component.css'
})
export class SimpleloginComponent {
  email: string = '';
  password: string = '';

  login() {
    // Placeholder for login logic
    console.log('Email:', this.email);
    console.log('Password:', this.password);

  }
}

This code snippet declares two properties: email, initialized to an empty string, and password, also initialized to an empty string. The login() method serves as a placeholder for the login logic. When invoked, it logs the current values of email and password to the console. This method can be expanded to include actual authentication functionality, such as verifying the user's credentials against a backend service.

<div><br>
    <h2>Login Form</h2>
    <form (ngSubmit)="login()">
      <div>
        <label for="email">Email:</label>
        <input type="email" id="email" [(ngModel)]="email" name="email" required />
      </div>
      <div>
        <label for="password">Password:</label>
        <input type="password" id="password" [(ngModel)]="password" name="password" required />
      </div>
      <button type="submit">Login</button>
    </form>
  </div>

This HTML code creates a simple login form with a header and two input fields for email and password. The form uses Angular's ngSubmit directive to trigger the login() method when submitted. Each input field is bound to the respective properties email and password using [(ngModel)] for two-way data binding. The required attribute ensures that both fields must be filled out before submission. The form includes a submit button labeled "Login," allowing users to submit their credentials for authentication.

OUTPUT:

#18 component name: bookmarklist

Allow users to input URLs and display them using anchor tags.

import { Component } from '@angular/core';

@Component({
  selector: 'app-bookmarklist',
  templateUrl: './bookmarklist.component.html',
  styleUrl: './bookmarklist.component.css'
})
export class BookmarklistComponent {
  url: string = '';
  bookmarks: string[] = [];

  addBookmark() {
    if (this.url) {
      this.bookmarks.push(this.url);
      this.url = ''; // Clear the input field
    }
  }
}

This code defines a property url, initialized as an empty string, and an array bookmarks to store the list of bookmark URLs. The addBookmark() method adds the current url to the bookmarks array if it's not empty. After adding the bookmark, it clears the url property, allowing the input field to be reset for the next entry. This method facilitates the dynamic addition of bookmarks to the list.

<div><br>
    <h2>Bookmark List</h2><br>
    <input type="text" [(ngModel)]="url" placeholder="Enter URL" />
    <button (click)="addBookmark()">Add Bookmark</button>

    <div *ngIf="bookmarks.length">
      <h3>Your Bookmarks</h3>
      <ul>
        <li *ngFor="let bookmark of bookmarks">
          <a [href]="bookmark" target="_blank">{{ bookmark }}</a>
        </li>
      </ul>
    </div>
  </div>

This HTML code creates an interface for a Bookmark List. It includes a header and an input field for entering a URL, bound to the url property using Angular's [(ngModel)] directive. A button triggers the addBookmark() method to add the entered URL to the bookmarks list. If the bookmarks array contains any items, a section displays the list of bookmarks with a subheader. Each bookmark is presented as a list item, using *ngFor to iterate over the bookmarks array. Each item is a hyperlink that opens the corresponding URL in a new tab, thanks to the target="_blank" attribute.

OUTPUT:

#19 component name: charactercounter

Input a string and count the number of characters in it.

import { Component } from '@angular/core';

@Component({
  selector: 'app-charactercounter',
  templateUrl: './charactercounter.component.html',
  styleUrl: './charactercounter.component.css'
})
export class CharactercounterComponent {
  inputString: string = '';
  characterCount: number = 0;

  countCharacters() {
    this.characterCount = this.inputString.length;
  }
}

This code defines an Angular component called CharactercounterComponent that counts characters in an input string. It has inputString for user input and characterCount to store the length. The countCharacters() method updates characterCount based on inputString length.

<div>
    <h2>Character Counter</h2>
    <textarea [(ngModel)]="inputString" (input)="countCharacters()" placeholder="Type your text here..."></textarea>
    <div *ngIf="characterCount >= 0">
      <p>Character Count: {{ characterCount }}</p>
    </div>
  </div>

This HTML code is part of the CharactercounterComponent and provides a user interface for counting characters. It includes a header and a textarea for user input, bound to inputString with [(ngModel)]. The (input) event triggers the countCharacters() method to update the character count. If characterCount is non-negative, it displays the current character count below the textarea.

OUTPUT:

#20 component name: palindromechecker

Input a word and check if it's a palindrome.

inputWord: string = '';
  isPalindrome: boolean | null = null;

  checkPalindrome() {
    const normalizedWord = this.inputWord.replace(/\s+/g, '').toLowerCase();
    this.isPalindrome = normalizedWord === normalizedWord.split('').reverse().join('');
  }

This code defines properties and a method for checking if a word is a palindrome in an Angular component. It has inputWord for user input and isPalindrome to store the result. The checkPalindrome() method normalizes inputWord by removing spaces and converting it to lowercase, then checks if it reads the same forwards and backwards, updating isPalindrome accordingly.

<div>
    <h2>Palindrome Checker</h2>
    <input type="text" [(ngModel)]="inputWord" (input)="checkPalindrome()" placeholder="Enter a word" />
    <div *ngIf="isPalindrome !== null">
      <p *ngIf="isPalindrome">The word is a palindrome!</p>
      <p *ngIf="!isPalindrome">The word is not a palindrome.</p>
    </div>
  </div>

This HTML code is part of a palindrome checker component. It includes a header and an input field for entering a word, bound to inputWord with [(ngModel)]. The (input) event calls checkPalindrome() to evaluate the input. If isPalindrome is not null, it conditionally displays messages indicating whether the word is a palindrome or not.

OUTPUT:

#21 component name: temperatureconverter

Convert temperature from Celsius to Fahrenheit and vice versa.

celsius: number | null = null;
  fahrenheit: number | null = null;

  convertToFahrenheit() {
    if (this.celsius !== null) {
      this.fahrenheit = this.celsius * 9 / 5 + 32;
    }
  }

  convertToCelsius() {
    if (this.fahrenheit !== null) {
      this.celsius = (this.fahrenheit - 32) * 5 / 9;
    }
  }

This code defines properties and methods for temperature conversion in an Angular component. It has celsius and fahrenheit to store input values. The convertToFahrenheit() method converts Celsius to Fahrenheit, while convertToCelsius() converts Fahrenheit to Celsius, updating the respective properties if the input is not null.

<div>
    <h2>Temperature Converter</h2>
    <div>
      <label for="celsius">Celsius:</label>
      <input type="number" id="celsius" [(ngModel)]="celsius" (input)="convertToFahrenheit()" placeholder="°C" />
      <span *ngIf="fahrenheit !== null">= {{ fahrenheit | number: '1.1-1' }} °F</span>
    </div>
    <div>
      <label for="fahrenheit">Fahrenheit:</label>
      <input type="number" id="fahrenheit" [(ngModel)]="fahrenheit" (input)="convertToCelsius()" placeholder="°F" />
      <span *ngIf="celsius !== null">= {{ celsius | number: '1.1-1' }} °C</span>
    </div>
  </div>

This HTML code is part of a temperature converter component. It includes a header and two input fields for Celsius and Fahrenheit. Each input is bound to the respective properties using [(ngModel)], with (input) events triggering the conversion methods. When a temperature is entered, it displays the converted value alongside the input field, using Angular's number pipe for formatting. The converted value is shown only if the corresponding property is not null.

OUTPUT:

#22 component name: shoppinglist

Create a shopping list where users can add and remove items (use list data structure).

 item: string = '';
  shoppingList: string[] = [];

  addItem() {
    if (this.item) {
      this.shoppingList.push(this.item);
      this.item = ''; // Clear the input field
    }
  }

  removeItem(index: number) {
    this.shoppingList.splice(index, 1);
  }

This code defines properties and methods for managing a shopping list in an Angular component. It has item for user input and shoppingList to store the list of items. The addItem() method adds the current item to the shoppingList if it's not empty, then clears the input. The removeItem(index: number) method removes an item from the list based on its index.

<div>
    <h2>Shopping List</h2>
    <input type="text" [(ngModel)]="item" placeholder="Add new item" />
    <button (click)="addItem()">Add</button>

    <ul>
      <li *ngFor="let item of shoppingList; let i = index">
        {{ item }} <button (click)="removeItem(i)">Remove</button>
      </li>
    </ul>
  </div>

This HTML code is part of a shopping list component. It includes a header, an input field for adding new items, and a button that calls the addItem() method. It displays the shoppingList as an unordered list, where each item is shown with a "Remove" button. The button calls the removeItem(i) method to remove the corresponding item based on its index.

OUTPUT:

#23 component name: factorialcalculator

Input a number and calculate its factorial when a button is clicked.

 number: number | null = null;
  factorial: number | null = null;

  calculateFactorial() {
    if (this.number !== null && this.number >= 0) {
      this.factorial = this.factorialRecursive(this.number);
    } else {
      this.factorial = null; // Reset if invalid input
    }
  }

  private factorialRecursive(n: number): number {
    return n <= 1 ? 1 : n * this.factorialRecursive(n - 1);
  }

This code defines properties and methods for calculating the factorial of a number in an Angular component. It has number for user input and factorial to store the result. The calculateFactorial() method checks if number is valid (non-null and non-negative) and computes the factorial using the recursive factorialRecursive(n) method. If the input is invalid, it resets factorial to null.

<div>
    <h2>Factorial Calculator</h2>
    <input type="number" [(ngModel)]="number" placeholder="Enter a non-negative number" />
    <button (click)="calculateFactorial()">Calculate Factorial</button>

    <div *ngIf="factorial !== null">
      <p>Factorial of {{ number }} is {{ factorial }}.</p>
    </div>
  </div>

This HTML code is part of a factorial calculator component. It includes a header, an input field for entering a non-negative number, and a button that triggers the calculateFactorial() method. If the factorial is not null, it displays the calculated factorial result for the entered number.

OUTPUT:

#24 component name: todomanager

Create a simple to-do list where users can add and remove tasks (use list data structure).

tasks: string[] = []; // List to store tasks
  newTask: string = ''; // Variable to hold the new task input

  addTask() {
    if (this.newTask.trim()) {
      this.tasks.push(this.newTask); // Add task to the list
      this.newTask = ''; // Clear the input field
    }
  }

  removeTask(index: number) {
    this.tasks.splice(index, 1); // Remove task by index
  }

This code manages a to-do list. It uses tasks to store tasks and newTask for the input. The addTask() function adds a non-empty task to the list and clears the input, while removeTask(index) deletes a task at the specified index. The key actions are adding and removing tasks from the list efficiently.

<div class="todo-container">
  <h2>To-Do Manager</h2>
  <input 
    type="text" 
    [(ngModel)]="newTask" 
    placeholder="Enter a task" 
    (keyup.enter)="addTask()" 
  />
  <button (click)="addTask()">Add Task</button>

  <ul>
    <li *ngFor="let task of tasks; index as i">
      {{ task }}
      <button (click)="removeTask(i)">Remove</button>
    </li>
  </ul>
</div>

This HTML code creates a to-do manager interface. An input field allows users to enter tasks, which are added when pressing Enter or clicking the "Add Task" button. The list of tasks is displayed inside an unordered list (ul) with each task as a list item (li). Each task has a "Remove" button that deletes the task. Key components are the input with ngModel binding for task input, and the *ngFor directive, which dynamically displays and manages tasks with their respective remove buttons.

OUTPUT:

#25 component name: guessnumbergame

Create a number guessing game where the user inputs guesses.

targetNumber: number = Math.floor(Math.random() * 100) + 1; // Random number between 1 and 100
  guess: number | null = null; // User's guess
  message: string = ''; // Feedback message

  checkGuess() {
    if (this.guess === null) return;

    if (this.guess < this.targetNumber) {
      this.message = 'Too low! Try again.';
    } else if (this.guess > this.targetNumber) {
      this.message = 'Too high! Try again.';
    } else {
      this.message = 'Congratulations! You guessed it right!';
      this.resetGame();
    }
  }

  resetGame() {
    this.targetNumber = Math.floor(Math.random() * 100) + 1;
    this.guess = null;
  }

This code implements a number guessing game. targetNumber is a random number between 1 and 100, and guess holds the user’s input. The checkGuess() function compares the guess with the target number and updates message with feedback: "Too low," "Too high," or "Congratulations!" on a correct guess. Upon a correct guess, resetGame() is called to start a new round by resetting the targetNumber and clearing the guess. The critical parts are the random number generation, guess checking, and game reset functionality.

<div class="game-container">
    <h2>Number Guessing Game</h2>
    <p>Guess a number between 1 and 100</p>
    <input 
      type="number" 
      [(ngModel)]="guess" 
      placeholder="Enter your guess" 
      (keyup.enter)="checkGuess()"
    />
    <button (click)="checkGuess()">Check Guess</button>

    <p>{{ message }}</p>
  </div>
  <div class="game-container">
    <h2>Number Guessing Game</h2>
    <p>Guess a number between 1 and 100</p>
    <input 
      type="number" 
      [(ngModel)]="guess" 
      placeholder="Enter your guess" 
      (keyup.enter)="checkGuess()"
    />
    <button (click)="checkGuess()">Check Guess</button>

    <p>{{ message }}</p>
  </div>

This HTML code sets up the user interface for a number guessing game. It features two identical game containers, each with a title and instructions. Each container has an input field for users to enter their guesses (bound to the guess variable) and a button to submit the guess. Pressing Enter or clicking the "Check Guess" button triggers the checkGuess() function to evaluate the input. The feedback message, displayed below the input, provides users with real-time updates on their guesses. The structure allows for easy duplication of the game, though typically, only one instance would be needed.

OUTPUT:

#26 component name: wordcounter

Input a string and count the number of words in it.

 inputText: string = '';
  wordCount: number = 0;

  countWords(): void {
    this.wordCount = this.inputText ? this.inputText.trim().split(/\s+/).length : 0;
  }

This TypeScript code implements a word counter with an inputText variable for user input and a wordCount variable for the total word count. The countWords() method checks if inputText is not empty, trims spaces, and splits the text using a regular expression (/\s+/) to count the words. If the input is empty, wordCount is set to 0. The primary function is the split method, which accurately counts words based on whitespace.

<div>
    <h2>Word Counter</h2>
    <textarea [(ngModel)]="inputText" (input)="countWords()" placeholder="Type your text here..." style="height: 50px;"></textarea>
    <p>Word Count: {{ wordCount }}</p>
  </div>

This HTML code creates a user interface for a word counter. It includes a header and a <textarea> for users to input their text, which is bound to the inputText variable. The (input) event triggers the countWords() method whenever the user types, updating the word count in real time. Below the textarea, the current word count is displayed using interpolation ({{ wordCount }}). This setup allows users to see how many words they’ve typed as they enter text.

OUTPUT:

#27 component name: randomnumbergenerator

Generate and display a random number between a specified range when a button is clicked.

import { Component } from '@angular/core';

@Component({
  selector: 'app-randomnumbergenerator',
  templateUrl: './randomnumbergenerator.component.html',
  styleUrl: './randomnumbergenerator.component.css'
})
export class RandomnumbergeneratorComponent {
  min: number = 1;
  max: number = 100;
  randomNumber: number | null = null;

  generateRandomNumber(): void {
    this.randomNumber = Math.floor(Math.random() * (this.max - this.min + 1)) + this.min;
  }
}

This TypeScript code defines a RandomnumbergeneratorComponent for generating random numbers in an Angular application. It sets initial values for min (1) and max (100) and declares randomNumber to hold the generated number. The generateRandomNumber() method calculates a random integer between min and max using the formula Math.floor(Math.random() * (this.max - this.min + 1)) + this.min, and assigns the result to randomNumber. This component effectively provides a mechanism to generate random numbers within a specified range.

<div>
    <h2>Random Number Generator</h2>
    <label for="min">Min:</label>
    <input type="number" id="min" [(ngModel)]="min" />

    <label for="max">Max:</label>
    <input type="number" id="max" [(ngModel)]="max" />

    <button (click)="generateRandomNumber()">Generate Random Number</button>

    <p *ngIf="randomNumber !== null">Random Number: {{ randomNumber }}</p>
  </div>

This HTML code creates a user interface for a random number generator. It includes a header and two input fields for users to set the minimum (min) and maximum (max) values, both bound to their respective variables using ngModel. A button triggers the generateRandomNumber() method when clicked. If a random number has been generated, it displays the result below the button using conditional rendering (*ngIf). This setup allows users to define a range and generate a random number within it easily.

OUTPUT:

#28 component name: multiplicationchecker

Check if a number is a multiple of another number.

number: number | null = null;
  multipleOf: number | null = null;
  isMultiple: boolean | null = null;

  checkMultiple(): void {
    if (this.number !== null && this.multipleOf !== null) {
      this.isMultiple = this.number % this.multipleOf === 0;
    } else {
      this.isMultiple = null;
    }
  }

This TypeScript code checks if a given number is a multiple of another number. It declares three variables: number to hold the user's input, multipleOf for the number to check against, and isMultiple to store the result (true, false, or null). The checkMultiple() method evaluates whether both number and multipleOf are not null. If they are valid, it checks if number is divisible by multipleOf using the modulus operator (%) and sets isMultiple accordingly. If either input is null, isMultiple is reset to null. This code effectively determines multiple relationships between two numbers.

<div>
    <h2>Multiplication Checker</h2>
    <label for="number">Number:</label>
    <input type="number" id="number" [(ngModel)]="number" />

    <label for="multipleOf">Multiple Of:</label>
    <input type="number" id="multipleOf" [(ngModel)]="multipleOf" />

    <button (click)="checkMultiple()">Check</button>

    <p *ngIf="isMultiple !== null">
      {{ number }} is {{ isMultiple ? '' : 'not ' }}a multiple of {{ multipleOf }}.
    </p>
  </div>

This HTML code creates a user interface for a multiplication checker. It includes a header and two input fields where users can enter a number and a value to check for multiples, both bound to the number and multipleOf variables using ngModel. A button labeled "Check" triggers the checkMultiple() method when clicked. If the result (isMultiple) is not null, it displays a message indicating whether the first number is a multiple of the second. The message dynamically updates based on the value of isMultiple, providing clear feedback to the user.

OUTPUT:

#29 component name: uppercaseconverter

Input a string and convert it to uppercase when the button is clicked.

import { Component } from '@angular/core';

@Component({
  selector: 'app-uppercaseconverter',
  templateUrl: './uppercaseconverter.component.html',
  styleUrl: './uppercaseconverter.component.css'
})
export class UppercaseconverterComponent {
  inputText: string = '';
  uppercasedText: string = '';

  convertToUppercase(): void {
    this.uppercasedText = this.inputText.toUpperCase();
  }
}

This TypeScript code defines an UppercaseconverterComponent that converts user input to uppercase. It has inputText for user input and uppercasedText for the result. The convertToUppercase() method converts inputText to uppercase using toUpperCase() and stores it in uppercasedText. This component allows for simple text transformation to uppercase.

<div>
    <h2>Uppercase Converter</h2>
    <input type="text" [(ngModel)]="inputText" placeholder="Type your text here..." />

    <button (click)="convertToUppercase()">Convert to Uppercase</button>

    <p *ngIf="uppercasedText">Converted Text: {{ uppercasedText }}</p>
  </div>

This HTML code creates a user interface for an uppercase converter. It includes a header and an input field for users to type text, which is bound to the inputText variable using ngModel. A button triggers the convertToUppercase() method when clicked. If there is a converted result, it displays the uppercase text below the button using conditional rendering (*ngIf). This setup allows users to easily convert and view their input text in uppercase.

OUTPUT:

#30 component name: wordshuffler

Input a word and shuffle its letters randomly.

import { Component } from '@angular/core';

@Component({
  selector: 'app-wordshuffler',
  templateUrl: './wordshuffler.component.html',
  styleUrl: './wordshuffler.component.css'
})
export class WordshufflerComponent {
  inputWord: string = '';
  shuffledWord: string = '';

  shuffleWord(): void {
    const letters = this.inputWord.split('');
    for (let i = letters.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [letters[i], letters[j]] = [letters[j], letters[i]]; // Swap
    }
    this.shuffledWord = letters.join('');
  }
}

This TypeScript code defines inputWord for user input and shuffledWord for the result. The shuffleWord() method splits inputWord into letters, randomly shuffles them using the Fisher-Yates algorithm, and then joins them back into a string assigned to shuffledWord. This enables random rearrangement of the input word's letters.

<div>
    <h2>Word Shuffler</h2>
    <input type="text" [(ngModel)]="inputWord" placeholder="Type your word here..." />

    <button (click)="shuffleWord()">Shuffle Word</button>

    <p *ngIf="shuffledWord">Shuffled Word: {{ shuffledWord }}</p>
  </div>

This code creates a word shuffler interface with an input field for users to enter a word (bound to inputWord). A button calls the shuffleWord() method to shuffle the letters. If a shuffled word exists, it displays the result below using conditional rendering. This setup allows users to shuffle and see their input word easily.

OUTPUT:

#31 component name: bmisolver

Input height and weight, calculate and display the BMI.

import { Component } from '@angular/core';

@Component({
  selector: 'app-bmisolver',
  templateUrl: './bmisolver.component.html',
  styleUrl: './bmisolver.component.css'
})
export class BmisolverComponent {
  height: number | null = null;  // Height in meters
  weight: number | null = null;  // Weight in kilograms
  bmi: number | null = null;

  calculateBMI(): void {
    if (this.height && this.weight) {
      this.bmi = this.weight / (this.height * this.height);
    } else {
      this.bmi = null;
    }
  }
}

This TypeScript code defines a BmisolverComponent that calculates BMI. It uses height and weight for user input and bmi to store the result. The calculateBMI() method computes BMI using the formula weight / (height * height) if both height and weight are provided; otherwise, it sets bmi to null. This component allows users to calculate BMI based on their height and weight.

<div>
    <h2>BMI Solver</h2>
    <label for="height">Height (in meters):</label>
    <input type="number" id="height" [(ngModel)]="height" step="0.01" />

    <label for="weight">Weight (in kilograms):</label>
    <input type="number" id="weight" [(ngModel)]="weight" step="0.1" />

    <button (click)="calculateBMI()">Calculate BMI</button>

    <p *ngIf="bmi !== null">Your BMI is: {{ bmi | number:'1.1-1' }}</p>
  </div>

This TypeScript code defines a BmisolverComponent that calculates BMI. It uses height and weight for user input and bmi to store the result. The calculateBMI() method computes BMI using the formula weight / (height * height) if both height and weight are provided; otherwise, it sets bmi to null. This component allows users to calculate BMI based on their height and weight.

OUTPUT:

#32 component name: usernamevalidator

Input a username and check its validity based on predefined rules (Create a variable).

import { Component } from '@angular/core';

@Component({
  selector: 'app-usernamevalidator',
  templateUrl: './usernamevalidator.component.html',
  styleUrl: './usernamevalidator.component.css'
})
export class UsernamevalidatorComponent {
  username: string = '';
  isValid: boolean | null = null;

  validateUsername(): void {
    this.isValid = this.username.length >= 5 && /^[a-zA-Z0-9]+$/.test(this.username);
  }
}

This TypeScript code defines a UsernamevalidatorComponent that validates a username. The validateUsername() method checks if the username is at least 5 characters long and only contains alphanumeric characters, updating the isValid variable based on the result.

<div>
    <input type="text" [(ngModel)]="username" placeholder="Enter username" />
    <button (click)="validateUsername()">Validate</button>
    <p *ngIf="isValid !== null">
      Username is {{ isValid ? 'valid' : 'invalid' }}.
    </p>
  </div>

This HTML code creates a username validator interface with an input field for entering a username (bound to username). A button triggers the validateUsername() method. The result is displayed below, showing whether the username is valid or invalid using conditional rendering (*ngIf).

OUTPUT:

At least 5 characters before it become valid.

#33 component name: interestcalculator

Input principal, rate, and time, and calculate simple interest.

import { Component } from '@angular/core';

@Component({
  selector: 'app-interestcalculator',
  templateUrl: './interestcalculator.component.html',
  styleUrl: './interestcalculator.component.css'
})
export class InterestcalculatorComponent {
  principal: number | null = null;
  rate: number | null = null;
  time: number | null = null;
  interest: number | null = null;

  //function to calculate the interest hehe
  calculateInterest(): void {
    if (this.principal !== null && this.rate !== null && this.time !== null) {
      this.interest = (this.principal * this.rate * this.time) / 100;
    }
  }
}

This TypeScript code defines variables for calculating simple interest: principal, rate, time, and interest. The calculateInterest() method computes interest using the formula (principal×rate×time)/100(\text{principal} \times \text{rate} \times \text{time}) / 100(principal×rate×time)/100, provided that none of the input values are null. This allows users to calculate interest based on their inputs.

<br>
<br>
<div>
    <input type="number" [(ngModel)]="principal" placeholder="Principal" />
    <input type="number" [(ngModel)]="rate" placeholder="Rate (%)" />
    <input type="number" [(ngModel)]="time" placeholder="Time (years)" />

    <button (click)="calculateInterest()">Calculate Interest</button>

    <p *ngIf="interest !== null">Simple Interest: {{ interest }}</p>
  </div>

This code creates a user interface for calculating simple interest. It includes input fields for the principal amount, interest rate, and time in years, all bound to their respective variables. A button triggers the calculateInterest() method to compute the interest. If the interest is calculated, it displays the result below the button using conditional rendering. This setup allows users to easily input values and see their calculated simple interest.

OUTPUT:

#34 component name: compoundinterestcalculator

Calculate compound interest when principal, rate, time, and frequency are input.

import { Component } from '@angular/core';

@Component({
  selector: 'app-compoundinterestcalculator',
  templateUrl: './compoundinterestcalculator.component.html',
  styleUrl: './compoundinterestcalculator.component.css'
})
export class CompoundinterestcalculatorComponent {
  principal: number | null = null;
  rate: number | null = null;
  time: number | null = null;
  frequency: number | null = null;
  compoundInterest: number | null = null;

  calculateCompoundInterest(): void {
    if (this.principal !== null && this.rate !== null && this.time !== null && this.frequency !== null) {
      const amount = this.principal * Math.pow((1 + (this.rate / (100 * this.frequency))), this.frequency * this.time);
      this.compoundInterest = amount - this.principal;
    }
  }
}

This TypeScript code sets up a way to calculate compound interest. It has variables for the principal, rate, time, frequency, and the calculated compound interest. The calculateCompoundInterest() method figures out the total amount using a formula and then finds the compound interest by subtracting the principal from that total. This helps users calculate how much interest they’ll earn over time.

<div>
    <input type="number" [(ngModel)]="principal" placeholder="Principal" />
    <input type="number" [(ngModel)]="rate" placeholder="Rate (%)" />
    <input type="number" [(ngModel)]="time" placeholder="Time (years)" />
    <input type="number" [(ngModel)]="frequency" placeholder="Frequency (times per year)" />

    <button (click)="calculateCompoundInterest()">Calculate Compound Interest</button>

    <p *ngIf="compoundInterest !== null">Compound Interest: {{ compoundInterest }}</p>
  </div>

Additionally, This HTML code creates a user interface for calculating compound interest. It includes input fields for the principal amount, interest rate, time in years, and frequency of compounding per year, all linked to their respective variables. A button triggers the CalculateCompoundinterest() function to compute the interest. If the compound interest is calculated, it displays the result below the button. This setup makes it easy for users to enter values and see their compound interest.

OUTPUT:

#35 component name: fibonaccigenerator

Generate and display the first N Fibonacci numbers when a button is clicked.

import { Component } from '@angular/core';

@Component({
  selector: 'app-fibonaccigenerator',
  templateUrl: './fibonaccigenerator.component.html',
  styleUrl: './fibonaccigenerator.component.css'
})
export class FibonaccigeneratorComponent {
  n: number | null = null;
  fibonacciNumbers: number[] = [];

  generateFibonacci(): void {
    this.fibonacciNumbers = [];
    if (this.n !== null && this.n > 0) {
      let a = 0, b = 1;
      for (let i = 0; i < this.n; i++) {
        this.fibonacciNumbers.push(a);
        [a, b] = [b, a + b]; // Swap values
      }
    }
  }
}

This TypeScript code defines a component for generating Fibonacci numbers. It has a variable n for the number of Fibonacci numbers to generate and an array fibonacciNumbers to store the results. The generateFibonacci() method clears the array and, if n is a positive number, calculates the Fibonacci sequence using a loop. It swaps the values of a and b to generate the next number in the sequence. This allows users to generate and see the specified number of Fibonacci numbers easily.

<div>
    <input type="number" [(ngModel)]="n" placeholder="Enter N" />

    <button (click)="generateFibonacci()">Generate Fibonacci</button>

    <p *ngIf="fibonacciNumbers.length > 0">Fibonacci Numbers: {{ fibonacciNumbers.join(', ') }}</p>
  </div>

This HTML code provides a user interface to generate Fibonacci numbers. It has an input for the number NNN and a button to generate the sequence. If Fibonacci numbers are created, they are displayed as a comma-separated list below the button.

OUTPUT:

#36 component name: oddsumcalculator

Input a number, and calculate the sum of odd numbers up to that number.

import { Component } from '@angular/core';

@Component({
  selector: 'app-oddsumcalculator',
  templateUrl: './oddsumcalculator.component.html',
  styleUrl: './oddsumcalculator.component.css'
})
export class OddsumcalculatorComponent {
  number: number | null = null;
  oddSum: number | null = null;

  calculateOddSum(): void {
    if (this.number !== null && this.number > 0) {
      this.oddSum = 0;
      for (let i = 1; i <= this.number; i += 2) {
        this.oddSum += i; // Sum odd numbers
      }
    }
  }
}

This TypeScript code sets up a way to calculate the sum of odd numbers. It has a variable number for the user's input and oddSum to store the result. The calculateOddSum() method checks if the input is positive and then sums all odd numbers up to that input using a loop. This helps users find the total of odd numbers easily.

<div>
    <input type="number" [(ngModel)]="number" placeholder="Enter a number" />

    <button (click)="calculateOddSum()">Calculate Odd Sum</button>

    <p *ngIf="oddSum !== null">Sum of odd numbers up to {{ number }}: {{ oddSum }}</p>
  </div>

This HTML code creates an interface for calculating the sum of odd numbers. It includes an input field for the user to enter a number and a button to trigger the calculateOddSum() function. If the sum is calculated, it displays the result below the button, showing the total of odd numbers up to the entered number. This setup allows users to easily input a value and see the sum of odd numbers.

OUTPUT:

#37 component name: currencyformatter

Input a number and format it as currency when a button is clicked (Dollar, Php, Euro - search euro conversion).

import { Component } from '@angular/core';

@Component({
  selector: 'app-fibonaccigenerator',
  templateUrl: './fibonaccigenerator.component.html',
  styleUrl: './fibonaccigenerator.component.css'
})
export class FibonaccigeneratorComponent {
  n: number | null = null;
  fibonacciNumbers: number[] = [];

  generateFibonacci(): void {
    this.fibonacciNumbers = [];
    if (this.n !== null && this.n > 0) {
      let a = 0, b = 1;
      for (let i = 0; i < this.n; i++) {
        this.fibonacciNumbers.push(a);
        [a, b] = [b, a + b]; // Swap values
      }
    }
  }
}

This TypeScript code generates Fibonacci numbers based on the user-defined input nnn. It initializes an array to hold the Fibonacci numbers and checks if nnn is valid (not null and greater than zero). The generateFibonacci() method uses a loop to calculate and store the first nnn Fibonacci numbers, starting with 0 and 1. The method updates the values using swapping, allowing users to easily generate the Fibonacci sequence.

<div>
    <input type="number" [(ngModel)]="n" placeholder="Enter N" />

    <button (click)="generateFibonacci()">Generate Fibonacci</button>

    <p *ngIf="fibonacciNumbers.length > 0">Fibonacci Numbers: {{ fibonacciNumbers.join(', ') }}</p>
  </div>

This HTML code creates a user interface for generating Fibonacci numbers. It includes an input field where users can enter a number nnn, a button to trigger the generateFibonacci() function, and a paragraph that displays the generated Fibonacci numbers. If any Fibonacci numbers have been calculated, they will be shown in a comma-separated list below the button, allowing users to see the sequence easily.

OUTPUT:

#38 component name: randomquotedisplay

Display a random quote when a button is clicked (use list data structures).

import { Component } from '@angular/core';

@Component({
  selector: 'app-randomquotedisplay',
  templateUrl: './randomquotedisplay.component.html',
  styleUrl: './randomquotedisplay.component.css'
})
export class RandomquotedisplayComponent {
  quotes: string[] = [
    "Kung kaya ng iba, ipagawa mo sa kanila – Rhed Aligan",
    "The mistakes gives you experience to learn how to make mistake again - Jonalyn Nebril",
    "Life isn't about finding yourself, life is about creating  yourself - George Bernard Shaw",
    "If you want live a happy, tie it to a goal, not to people or things - Albert Einstein",
    "A goal without a plan is just a wish - Antoine de Saint Exupery",
    "You have to go able to get up and dust yourself off and always be going forward -Rita Moreno",
    "Better to fight for something than live for nothing - George S. Patton",
  ];
  randomQuote: string | null = null;

  displayRandomQuote(): void {
    const randomIndex = Math.floor(Math.random() * this.quotes.length);
    this.randomQuote = this.quotes[randomIndex];
  }
}

This TypeScript code defines an array of motivational quotes and a variable to hold a randomly selected quote. The displayRandomQuote() method generates a random index based on the array length and assigns a quote from the quotes array to randomQuote. This allows users to display a different motivational quote each time the method is called, enhancing the user experience with inspiration.

<div>
    <button (click)="displayRandomQuote()">Get Random Quote</button>
    <p *ngIf="randomQuote">{{ randomQuote }}</p>
  </div>

This HTML code creates a simple user interface for displaying random quotes. It includes a button that, when clicked, triggers the displayRandomQuote() method to select and show a random quote from the predefined array. Below the button, a paragraph element is conditionally rendered to display the randomQuote. If a quote is available, it will be shown, providing users with motivational or inspirational messages at the click of a button.

OUTPUT:

#39 component name: uppercasegreeting

User inputs their name, and when the button is clicked, display the name in uppercase.

import { Component } from '@angular/core';

@Component({
  selector: 'app-uppercasegreeting',
  templateUrl: './uppercasegreeting.component.html',
  styleUrl: './uppercasegreeting.component.css'
})
export class UppercasegreetingComponent {
  name: string = '';
  uppercaseName: string | null = null;

  displayUppercaseName(): void {
    this.uppercaseName = this.name.toUpperCase();
  }
}

This code snippet defines a simple component for converting a user's input name to uppercase. It has a name property to hold the input string and an uppercaseName property to store the converted uppercase version. The displayUppercaseName() method takes the value from name, converts it to uppercase using the toUpperCase() method, and assigns it to uppercaseName. This allows the program to display the uppercase version of the name whenever the method is called.

<div>
    <input type="text" [(ngModel)]="name" placeholder="Enter your name" />
    <button (click)="displayUppercaseName()">Submit</button>
    <p *ngIf="uppercaseName">Hello, {{ uppercaseName }}!</p>
  </div>

This HTML snippet allows users to input their name and displays a greeting in uppercase. It has an input field bound to the name property, a button that triggers the displayUppercaseName() method, and a paragraph that shows the uppercase greeting if uppercaseName is set. When the button is clicked, the input name is converted to uppercase, and the greeting "Hello, [Uppercase Name]!" is displayed.

OUTPUT:

#40 component name: divisiblechecker

Input two numbers, and check if the first is divisible by the second.

import { Component } from '@angular/core';

@Component({
  selector: 'app-divisiblechecker',
  templateUrl: './divisiblechecker.component.html',
  styleUrl: './divisiblechecker.component.css'
})
export class DivisiblecheckerComponent {
  number1: number | null = null;
  number2: number | null = null;
  isDivisible: boolean | null = null;

  checkDivisibility(): void {
    if (this.number1 !== null && this.number2 !== null && this.number2 !== 0) {
      this.isDivisible = this.number1 % this.number2 === 0;
    } else {
      this.isDivisible = null; // Reset if invalid input
    }
  }
}

This code checks if number1 is divisible by number2. When the checkDivisibility() method is called, it verifies that both numbers are valid and that number2 is not zero. If true, it checks whether number1 is divisible by number2. If not, or if the input is invalid, it resets the isDivisible property to null.

<div>
    <input type="number" [(ngModel)]="number1" placeholder="Enter first number" />
    <input type="number" [(ngModel)]="number2" placeholder="Enter second number" />
    <button (click)="checkDivisibility()">Check Divisibility</button>

    <p *ngIf="isDivisible !== null">
      {{ number1 }} is {{ isDivisible ? '' : 'not ' }}divisible by {{ number2 }}.
    </p>
  </div>

This code allows users to check if one number is divisible by another. It features two input fields for entering number1 and number2, and a button that triggers the checkDivisibility() method. If the numbers are valid, it displays whether number1 is divisible by number2. If the check is successful, it shows the message accordingly; otherwise, it will indicate that it is not divisible or reset the result if the inputs are invalid.

OUTPUT:

ADDITIONAL 10:

#41: ChangeColor

When i click the button, the background will change color randomly.

import { Component } from '@angular/core';

@Component({
  selector: 'app-changecolor',
  templateUrl: './changecolor.component.html',
  styleUrl: './changecolor.component.css'
})
export class ChangecolorComponent {
  colors = ['red', 'blue', 'green', 'yellow', 'purple'];
  currentColor = 'white';

  changeColor() {
    const randomIndex = Math.floor(Math.random() * this.colors.length);
    this.currentColor = this.colors[randomIndex];
  }
}

This code defines an Angular component that changes the background color to a random color from a predefined list. The ChangecolorComponent has a list of colors (colors) and a default background color (currentColor). The changeColor() method selects a random color from the list, changing the currentColor property. When invoked, it updates the background to the randomly chosen color.

<div [style.background-color]="currentColor" class="color-box">
    <p>Click the button to change the background color!</p>
    <button (click)="changeColor()">Change Color</button>
  </div>

This HTML snippet creates a box with a background color that can be changed by clicking a button. The div uses Angular's property binding to dynamically set its background-color using the currentColor variable. When the "Change Color" button is clicked, it triggers the changeColor() method to update the background color to a random color from the list in the component.

OUTPUT:

#42 EmojiGenerate

Generate emoji based on the array provided by clicking button

import { Component } from '@angular/core';

@Component({
  selector: 'app-emojigenerator',
  templateUrl: './emojigenerator.component.html',
  styleUrl: './emojigenerator.component.css'
})
export class EmojigeneratorComponent {
  emojis = ['😀', '😂', '😍', '🤔', '😎', '😢', '😡'];
  currentEmoji = '';

  generateEmoji() {
    const randomIndex = Math.floor(Math.random() * this.emojis.length);
    this.currentEmoji = this.emojis[randomIndex];
  }
}

This component randomly generates an emoji when the generateEmoji() method is called. It selects an emoji from a predefined list of emojis and displays it by updating the currentEmoji variable with a randomly selected emoji from the array.

<div>
    <h3>Random Emoji Generator</h3>
    <p *ngIf="currentEmoji" style="font-size: 50px;">{{ currentEmoji }}</p>
    <button (click)="generateEmoji()">Get Emoji</button>
  </div>

This HTML template provides a simple interface for the Random Emoji Generator. When the button is clicked, it triggers the generateEmoji() function, displaying a randomly selected emoji in large font size.

OUTPUT:

#43 PasswordStrength

import { Component } from '@angular/core';

@Component({
  selector: 'app-passwordstrength',
  templateUrl: './passwordstrength.component.html',
  styleUrl: './passwordstrength.component.css'
})
export class PasswordstrengthComponent {
  password: string = '';
  strength: string = '';

  checkStrength() {
    const length = this.password.length;
    if (length > 8) {
      this.strength = 'Strong';
    } else if (length >= 5) {
      this.strength = 'Moderate';
    } else {
      this.strength = 'Weak';
    }
  }
}

This PasswordstrengthComponent class assesses the strength of a password based on its length. If the password is longer than 8 characters, it is classified as "Strong." A length between 5 and 8 characters is considered "Moderate," and anything shorter is labeled "Weak." The checkStrength() method updates the strength variable based on the password's length.

<div>
    <input type="password" [(ngModel)]="password" (input)="checkStrength()" placeholder="Enter password">
    <p>Password strength: {{ strength }}</p>
  </div>

This code lets users input a password and displays its strength (Weak, Moderate, Strong) based on its length, updating in real time.

OUTPUT:

#44: ColorPicker

When click the button it show the color and the rgb code.

import { Component } from '@angular/core';

@Component({
  selector: 'app-colorpicker',
  templateUrl: './colorpicker.component.html',
  styleUrl: './colorpicker.component.css'
})
export class ColorpickerComponent {
  colors: string[] = ['Red #FF0000', 'Green #00FF00', 'Blue #0000FF'];
  selectedColor: string = 'None'; // Default value

  onSelectColor(color: string): void {
    this.selectedColor = color;
  }
}

This code defines a list of color names with their hex codes and updates the selectedColor property when a user selects a color.

<div>
  <h2>Select a Color</h2>

  <div>
    <button (click)="onSelectColor('Red #FF0000')">Red</button>
    <button (click)="onSelectColor('Green #00FF00')">Green</button>
    <button (click)="onSelectColor('Blue #0000FF')">Blue</button>
  </div>

  <div>
    <p>Selected Color: {{ selectedColor }}</p>
  </div>
</div>

This HTML template allows users to select a color by clicking one of the buttons (Red, Green, or Blue), which updates and displays the selectedColor value below the buttons.

OUTPUT:

#45 simplequiz

It only 1 question with a correct answer.

import { Component } from '@angular/core';

@Component({
  selector: 'app-simplequiz',
  templateUrl: './simplequiz.component.html',
  styleUrl: './simplequiz.component.css'
})
export class SimplequizComponent {

  question = {
    question: "Ano ang capital ng Philippines?",
    options: ["South China Sea", "Palawan", "Letter P", "Manila"],
    correctAnswer: "Manila"
  };

  selectedAnswer: string = ''; // dito nialalgay yung user's selected answer
  result: string = '';         // maghohold the result message

  // Function to handle answer selection
  selectAnswer(answer: string): void {
    this.selectedAnswer = answer;

    // Check if the selected answer is correct
    if (answer === this.question.correctAnswer) {
      this.result = 'Correct!';
    } else {
      this.result = 'Incorrect!';
    }
  }
}

This code creates a simple quiz that asks about the capital of the Philippines. It uses a question object containing the question, options, and the correct answer. The selectAnswer function updates the user's selected answer and checks if it's correct, setting a feedback message as 'Correct!' or 'Incorrect!' based on the user's choice.

<div>
    <h2>Quiz ni Rhed pero isa lang</h2>

    <p>{{ question.question }}</p> <!-- ito ay tawag na data binding-->

    <!-- Display the multiple choice options as buttons -->
    <div *ngFor="let option of question.options">
      <button (click)="selectAnswer(option)">{{ option }}</button>
    </div>

    <!-- ang variable na result gumamit ako ng *ngIf for true or false -->
    <div *ngIf="result">
      <p *ngIf="result !== null">Ang "{{ selectedAnswer }}", ay {{ result }}</p>
    </div>
  </div>

This code displays a quiz interface where a question and its multiple-choice options are presented. The question is bound to the view using Angular's data binding syntax. Each option is rendered as a button, and when a button is clicked, it calls the selectAnswer function, passing the selected option. The result of the user's choice is shown conditionally using *ngIf, which displays a message indicating whether the selected answer is correct or incorrect, along with the user's selected answer.

OUTPUT:

#46 TimerCountdown

I set 1min, 5min, and 10 min button when it click then the countdown started.

import { Component } from '@angular/core';

@Component({
  selector: 'app-timer',
  templateUrl: './timer.component.html',
  styleUrl: './timer.component.css'
})
export class TimerComponent {
  countdown: number = 0;  // Countdown value in seconds
  interval: any;
  countdownMessage: string = ''; // To hold the countdown message

  startTimer(minutes: number): void {
    this.countdown = minutes * 60; // Conversion from minutes to seconds
    this.countdownMessage = `Countdown started for ${minutes} minute(s)`; // Set the countdown message

    clearInterval(this.interval); // Clear any existing timer
    this.interval = setInterval(() => {
      if (this.countdown > 0) {
        this.countdown--;
      } else {
        clearInterval(this.interval); // Clear when countdown reaches zero
        this.countdownMessage = ''; // Clear the message when time is up
      }
    }, 1000);
  }
}

This code implements a countdown timer that starts based on a specified number of minutes. The countdown variable tracks the time left in seconds, and countdownMessage displays a message indicating the timer has started. The startTimer method converts minutes to seconds, sets the countdown message, and ensures any existing timer is cleared. Using setInterval, it decrements the countdown every second. When the countdown reaches zero, the timer stops, and the message is cleared.

<div>
    <h2>Countdown Timer</h2>

    <button (click)="startTimer(1)">1 Minute</button>
    <button (click)="startTimer(5)">5 Minutes</button>
    <button (click)="startTimer(10)">10 Minutes</button>

    <!-- Display the countdown message -->
    <p *ngIf="countdownMessage">{{ countdownMessage }}</p>

    <!-- Display time left -->
    <p *ngIf="countdown > 0">Time left: {{ countdown }} seconds</p>
    <p *ngIf="countdown === 0">Time is up!</p>
  </div>

This code creates a countdown timer interface in Angular. It includes buttons to start the timer for 1, 5, or 10 minutes. When a button is clicked, the startTimer function is called with the corresponding time. The timer displays a message indicating the countdown has started and shows the remaining time in seconds. When the countdown reaches zero, it displays a "Time is up!" message. The countdown message and the remaining time are conditionally displayed based on the timer's state.

OUTPUT:

#47: Color Name to Hex Converter

The text input will convert into the hex code color.

import { Component } from '@angular/core';

@Component({
  selector: 'app-colornametohex',
  templateUrl: './colornametohex.component.html',
  styleUrl: './colornametohex.component.css'
})
export class ColornametohexComponent {
  colorName: string = ''; // User input for color name
  hexValue: string = '';  // Resulting hexadecimal value

  // A mapping of color names to their hexadecimal values
  colorMap: { [key: string]: string } = {
    red: '#FF0000',
    green: '#008000',
    blue: '#0000FF',
    yellow: '#FFFF00',
    orange: '#FFA500',
    purple: '#800080',
    black: '#000000',
    white: '#FFFFFF',
    pink: '#FFC0CB',
    brown: '#A52A2A',
    // Add more colors as needed
  };

  // Function to convert color name to hex
  convertColorNameToHex(): void {
    const color = this.colorMap[this.colorName.toLowerCase()]; // Get hex value from map
    this.hexValue = color ? color : 'Invalid color name'; // Set hex value or error message
  }
}

This code defines a color conversion feature in Angular. It includes a user input for a color name (colorName) and outputs the corresponding hexadecimal value (hexValue). A colorMap object maps common color names to their hexadecimal representations. The convertColorNameToHex function retrieves the hex value from the colorMap based on the user's input, converting the input to lowercase for case-insensitive matching. If a valid color name is provided, it updates hexValue with the corresponding hex; otherwise, it sets an error message indicating the color name is invalid.

<div>
    <h2>Color Name to Hex Converter</h2>

    <label for="colorName">Enter a color name:</label>
    <input type="text" id="colorName" [(ngModel)]="colorName" />
    <button (click)="convertColorNameToHex()">Convert</button>

    <p *ngIf="hexValue">Hexadecimal Value: {{ hexValue }}</p>
  </div>

This Angular component converts a color name to its hexadecimal value. Users enter a color in a text field, and upon clicking "Convert," the convertColorNameToHex function checks a predefined mapping. If the color is valid, it displays the corresponding hex value; otherwise, it indicates an invalid color name.

OUTPUT:

#48: List contact List

Allow user input the contact information.

import { Component } from '@angular/core';

@Component({
  selector: 'app-contactlist',
  templateUrl: './contactlist.component.html',
  styleUrl: './contactlist.component.css'
})
export class ContactlistComponent {
  name: string = '';          // User's name
  phoneNumber: string = '';   // User's phone number
  contacts: { name: string, phone: string }[] = []; // Array to hold contacts

  // Function to add a contact
  addContact(): void {
    if (this.name && this.phoneNumber) {
      this.contacts.push({ name: this.name, phone: this.phoneNumber }); // Add contact to the array
      this.name = '';          // Clear name input
      this.phoneNumber = '';   // Clear phone number input
    }
  }
}

This Angular component manages a simple contact list. It allows users to input their name and phone number. The addContact function checks if both fields are filled, and if so, it adds the contact to an array. After adding, it clears the input fields for new entries.

<div>
    <h2>Contact List</h2>

    <label for="name">Name:</label>
    <input type="text" id="name" [(ngModel)]="name" />

    <label for="phone">Phone Number:</label>
    <input type="text" id="phone" [(ngModel)]="phoneNumber" />

    <button (click)="addContact()">Add Contact</button>

    <h3>Contact List:</h3>
    <ul>
      <li *ngFor="let contact of contacts">
        {{ contact.name }} - {{ contact.phone }}
      </li>
    </ul>
  </div>

This Angular component creates a contact list application. Users can enter a name and phone number, and when they click the "Add Contact" button, the details are added to a list displayed below. The contacts are shown as list items, with each displaying the name and phone number, leveraging Angular's *ngFor directive for rendering the list dynamically.

OUTPUT:

#49: Joke Generator

Generate random jokes based on the array that will display when button clicks

import { Component } from '@angular/core';

@Component({
  selector: 'app-jokegenerator',
  templateUrl: './jokegenerator.component.html',
  styleUrl: './jokegenerator.component.css'
})
export class JokegeneratorComponent {
  jokes: string[] = [
    "Anong tawag ng 0 kay 8? Wow ang sexy mo namann",
    "Bakit hindi pwede magtanim ng gulay sa Mars? Kasi wala silang 'space'!",
    "Bakit masakit magmahal ngayon? Kasi pag nasaktan ka, hindi ka na makakakain!"
  ];

  currentJoke: string = ''; // Store the current joke

  // Function to generate a random joke
  generateJoke(): void {
    const randomIndex = Math.floor(Math.random() * this.jokes.length);
    this.currentJoke = this.jokes[randomIndex];
  }
}

This Angular code defines a list of jokes and a function to randomly select and display one. The generateJoke function selects a random joke by generating a random index, and the selected joke is stored in currentJoke, ready to be displayed in the template.

<div>
    <h2>Random Joke Generator</h2>

    <button (click)="generateJoke()">Show Joke</button>

    <p *ngIf="currentJoke">{{ currentJoke }}</p>
  </div>

This template creates a "Random Joke Generator" with a button that triggers the generateJoke function. When clicked, a random joke from the predefined list is displayed in a <p> tag using Angular's data binding, showing the selected joke if one is available.

OUTPUT:

#50 Sentence Case Converter

This component display proper sentence character.

import { Component } from '@angular/core';

@Component({
  selector: 'app-sentencecaseconverter',
  templateUrl: './sentencecaseconverter.component.html',
  styleUrl: './sentencecaseconverter.component.css'
})
export class SentencecaseconverterComponent {
  inputText: string = '';
  convertedText: string = '';

  // Function to convert input to sentence case
  convertToSentenceCase(): void {
    if (this.inputText.length > 0) {
      this.convertedText = this.inputText.charAt(0).toUpperCase() + this.inputText.slice(1).toLowerCase();
    } else {
      this.convertedText = '';
    }
  }
}

This code takes an input string (inputText) and converts it to sentence case. The first character is capitalized, and the rest is converted to lowercase. If the input is empty, the result (convertedText) will also be an empty string.

<div>
    <h2>Sentence Case Converter</h2>

    <label for="sentence">Enter your sentence:</label>
    <input type="text" id="sentence" [(ngModel)]="inputText" />

    <button (click)="convertToSentenceCase()">Convert</button>

    <p *ngIf="convertedText">Converted Sentence: {{ convertedText }}</p>
  </div>

This form allows users to input a sentence, which is then converted to sentence case when the "Convert" button is clicked. The converted sentence is displayed below the input field if it exists. The binding connects the input field ([(ngModel)]="inputText") and the conversion result ({{ convertedText }}).

OUTPUT:

This is how add each folder, to commit and push to my GitHub repository

Check at the Github Repository the 50 components

In branch main, I commit and push all project BUT,

in master branch, for 1 by 1 folder COMMIT and PUSH:

then in my main branch use to add all components of angular project.

https://github.com/Rhedaligan8/Angular50Components.git

https://github.com/Rhedaligan8/Angular50Components.git

https://github.com/Rhedaligan8/Angular50Components.git

using - - standalone=false use to make all components not been standalone.

CREATING 40 provides different components under named “components” folder include the 10 additional components

During generating/creating folders above, it displays real-time process in CLI, some of its below: