ACTIVITY 14: Angular Components
First create your Angular Folder in CMD
ng new AngularComponent
Before creating component, navigate first to your project/file directory:
cd C:\Users\Teacher\AngularComponent
Create a Component Use the Angular CLI command to generate a new component.
I use 1 example code only
ng generate component components/displayhelloworld
I created 1 component already
then create the rest of components…
Locate your Angular file, open your VS code or any editor application you may use:
Select your File
Go to src/app and create app.module.ts
for importing, routing, declarations, providers, and bootstraps.
Right click then create a new file:
import { RouterModule, Routes } from "@angular/router";
import { AppComponent } from "./app.component";
import { NgModule } from "@angular/core";
import { CommonModule, CurrencyPipe, UpperCasePipe } from "@angular/common";
import { BrowserModule } from "@angular/platform-browser";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { DisplayhelloworldComponent } from "./components/displayhelloworld/displayhelloworld.component";
import { ShowhellobuttonComponent } from "./components/showhellobutton/showhellobutton.component";
import { DisplaynameComponent } from "./components/displayname/displayname.component";
import { FormsModule } from "@angular/forms";
import { CounterComponent } from "./components/counter/counter.component";
import { SimpleformComponent } from "./components/simpleform/simpleform.component";
import { UserageComponent } from "./components/userage/userage.component";
import { UsergreetingComponent } from "./components/usergreeting/usergreeting.component";
import { CalculatorComponent } from "./components/calculator/calculator.component";
import { TextlengthComponent } from "./components/textlength/textlength.component";
import { CurrencyconverterComponent } from "./components/currencyconverter/currencyconverter.component";
import { EvenoddcheckerComponent } from "./components/evenoddchecker/evenoddchecker.component";
import { WordreverserComponent } from "./components/wordreverser/wordreverser.component";
import { ShowdateComponent } from "./components/showdate/showdate.component";
import { ShowusernameComponent } from "./components/showusername/showusername.component";
import { MultiplicationtableComponent } from "./components/multiplicationtable/multiplicationtable.component";
import { SimpleloginComponent } from "./components/simplelogin/simplelogin.component";
import { FahrenheittocelsiusComponent } from "./components/fahrenheittocelsius/fahrenheittocelsius.component";
import { BookmarklistComponent } from "./components/bookmarklist/bookmarklist.component";
import { CharactercounterComponent } from "./components/charactercounter/charactercounter.component";
import { PalindromecheckerComponent } from "./components/palindromechecker/palindromechecker.component";
import { TemperatureconverterComponent } from "./components/temperatureconverter/temperatureconverter.component";
import { ShoppinglistComponent } from "./components/shoppinglist/shoppinglist.component";
import { FactorialcalculatorComponent } from "./components/factorialcalculator/factorialcalculator.component";
import { TodomanagerComponent } from "./components/todomanager/todomanager.component";
import { GuessnumbergameComponent } from "./components/guessnumbergame/guessnumbergame.component";
import { WordcounterComponent } from "./components/wordcounter/wordcounter.component";
import { RandomnumbergeneratorComponent } from "./components/randomnumbergenerator/randomnumbergenerator.component";
import { MultiplicationcheckerComponent } from "./components/multiplicationchecker/multiplicationchecker.component";
import { UppercaseconverterComponent } from "./components/uppercaseconverter/uppercaseconverter.component";
import { WordshufflerComponent } from "./components/wordshuffler/wordshuffler.component";
import { BmisolverComponent } from "./components/bmisolver/bmisolver.component";
import { UsernamevalidatorComponent } from "./components/usernamevalidator/usernamevalidator.component";
import { InterestcalculatorComponent } from "./components/interestcalculator/interestcalculator.component";
import { CompoundinterestcalculatorComponent } from "./components/compoundinterestcalculator/compoundinterestcalculator.component";
import { FibonaccigeneratorComponent } from "./components/fibonaccigenerator/fibonaccigenerator.component";
import { OddsumcalculatorComponent } from "./components/oddsumcalculator/oddsumcalculator.component";
import { CurrencyformatterComponent } from "./components/currencyformatter/currencyformatter.component";
import { RandomquotedisplayComponent } from "./components/randomquotedisplay/randomquotedisplay.component";
import { UppercasegreetingComponent } from "./components/uppercasegreeting/uppercasegreeting.component";
import { DivisiblecheckerComponent } from "./components/divisiblechecker/divisiblechecker.component";
import { StopwatchComponent } from "./components/stopwatch/stopwatch.component";
import { CountdowntimerComponent } from "./components/countdowntimer/countdowntimer.component";
import { PasswordstrengthcheckerComponent } from "./components/passwordstrengthchecker/passwordstrengthchecker.component";
import { UnitconverterComponent } from "./components/unitconverter/unitconverter.component";
import { SimplevotingComponent } from "./components/simplevoting/simplevoting.component";
import { DicerollerComponent } from "./components/diceroller/diceroller.component";
import { RandomcolorComponent } from "./components/randomcolor/randomcolor.component";
import { LettercomparisonComponent } from "./components/lettercomparison/lettercomparison.component";
import { PalindromenumberComponent } from "./components/palindromenumber/palindromenumber.component";
import { DaysuntilbirthdayComponent } from "./components/daysuntilbirthday/daysuntilbirthday.component";
const routes: Routes = [
{path: '', component: DisplayhelloworldComponent},
{path: 'showhellobutton', component: ShowhellobuttonComponent},
{path: 'displayname', component: DisplaynameComponent},
{path: 'counter', component: CounterComponent},
{path: 'simpleform', component: SimpleformComponent},
{path: 'userage', component: UserageComponent},
{path: 'usergreeting', component: UsergreetingComponent},
{path: 'calculator', component: CalculatorComponent},
{path: 'textlength', component: TextlengthComponent},
{path: 'currencyconverter', component: CurrencyconverterComponent},
{path: 'evenoddchecker', component: EvenoddcheckerComponent},
{path: 'wordreverser', component: WordreverserComponent},
{path: 'showdate', component: ShowdateComponent},
{path: 'showusername', component: ShowusernameComponent},
{path: 'multiplicationtable', component: MultiplicationtableComponent},
{path: 'simplelogin', component: SimpleloginComponent},
{path: 'fahrenheittocelsius', component: FahrenheittocelsiusComponent},
{path: 'bookmarklist', component: BookmarklistComponent},
{path: 'charactercounter', component: CharactercounterComponent},
{path: 'palindromechecker', component: PalindromecheckerComponent},
{path: 'temperatureconverter', component: TemperatureconverterComponent},
{path: 'shoppinglist', component: ShoppinglistComponent},
{path: 'factorialcalculator', component: FactorialcalculatorComponent},
{path: 'todomanager', component: TodomanagerComponent},
{path: 'guessnumbergame', component: GuessnumbergameComponent},
{path: 'wordcounter', component: WordcounterComponent},
{path: 'randomnumbergenerator', component: RandomnumbergeneratorComponent},
{path: 'multiplicationchecker', component: MultiplicationcheckerComponent},
{path: 'uppercaseconverter', component: UppercaseconverterComponent},
{path: 'wordshuffler', component: WordshufflerComponent},
{path: 'bmisolver', component: BmisolverComponent},
{path: 'usernamevalidator', component: UsernamevalidatorComponent},
{path: 'interestcalculator', component: InterestcalculatorComponent},
{path: 'compoundinterestcalculator', component: CompoundinterestcalculatorComponent},
{path: 'fibonaccigenerator', component: FibonaccigeneratorComponent},
{path: 'oddsumcalculator', component: OddsumcalculatorComponent},
{path: 'currencyformatter', component: CurrencyformatterComponent},
{path: 'randomquotedisplay', component: RandomquotedisplayComponent},
{path: 'uppercasegreeting', component: UppercasegreetingComponent},
{path: 'divisiblechecker', component: DivisiblecheckerComponent},
{path: 'stopwatch', component: StopwatchComponent},
{path: 'countdowntimer', component: CountdowntimerComponent},
{path: 'passwordstrengthchecker', component: PasswordstrengthcheckerComponent},
{path: 'unitconverter', component: UnitconverterComponent},
{path: 'simplevoting', component: SimplevotingComponent},
{path: 'diceroller', component: DicerollerComponent},
{path: 'randomcolor', component: RandomcolorComponent},
{path: 'lettercomparison', component: LettercomparisonComponent},
{path: 'palindromenumber', component: PalindromenumberComponent},
{path: 'daysuntilbirthday', component: DaysuntilbirthdayComponent},
]
@NgModule ({
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
RouterModule.forRoot(routes, {enableTracing: true}),
FormsModule,
],
declarations: [
AppComponent,
DisplayhelloworldComponent,
ShowhellobuttonComponent,
DisplaynameComponent,
CounterComponent,
SimpleformComponent,
UserageComponent,
UsergreetingComponent,
CalculatorComponent,
TextlengthComponent,
CurrencyconverterComponent,
EvenoddcheckerComponent,
WordreverserComponent,
ShowdateComponent,
ShowusernameComponent,
MultiplicationtableComponent,
SimpleloginComponent,
FahrenheittocelsiusComponent,
BookmarklistComponent,
CharactercounterComponent,
PalindromecheckerComponent,
TemperatureconverterComponent,
ShoppinglistComponent,
FactorialcalculatorComponent,
TodomanagerComponent,
GuessnumbergameComponent,
WordcounterComponent,
RandomnumbergeneratorComponent,
MultiplicationcheckerComponent,
UppercaseconverterComponent,
WordshufflerComponent,
BmisolverComponent,
UsernamevalidatorComponent,
InterestcalculatorComponent,
CompoundinterestcalculatorComponent,
FibonaccigeneratorComponent,
OddsumcalculatorComponent,
CurrencyformatterComponent,
RandomquotedisplayComponent,
UppercasegreetingComponent,
DivisiblecheckerComponent,
StopwatchComponent,
CountdowntimerComponent,
PasswordstrengthcheckerComponent,
UnitconverterComponent,
SimplevotingComponent,
DicerollerComponent,
RandomcolorComponent,
LettercomparisonComponent,
PalindromenumberComponent,
DaysuntilbirthdayComponent,
],
providers: [
],
bootstrap: [
AppComponent
]
})
export class AppModule {}
Now, in each component, you'll write the logic (in the TypeScript file) and the structure (in the HTML file)
To modify each component, locate the files 'file-name.component.ts'
for the TypeScript logic and 'file-name.component.html'
for the HTML structure
.html displayhelloworld
<h1>HELLO WORLD!!</h1>
using HTML <h1> to display Word
.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-displayhelloworld',
templateUrl: './displayhelloworld.component.html',
styleUrl: './displayhelloworld.component.css'
})
export class DisplayhelloworldComponent {
}
.html showhellobutton
<button (click)="showMessage()">Show Hello World</button>
<h1>{{message}}</h1>
.ts
Create a button and a <h1> to show the message
import { Component } from '@angular/core';
@Component({
selector: 'app-showhellobutton',
templateUrl: './showhellobutton.component.html',
styleUrl: './showhellobutton.component.css'
})
export class ShowhellobuttonComponent {
message: string = '';
showMessage() {
this.message = 'Hello World';
}
}
use variable to call the string
.html displayname
<input type = "text" placeholder="Input Name" [(ngModel)] = "name">
<br>
<br>
<button type="button" (click)="show()">Show</button>
<br>
<h1>{{displayname}}</h1>
Use input type text to input text and button to show result
.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-displayname',
templateUrl: './displayname.component.html',
styleUrl: './displayname.component.css'
})
export class DisplaynameComponent {
name: string = "";
displayname: string = "";
show() {
this.displayname = this.name
}
}
user can input their name, and upon clicking a button, their name will be displayed on the screen.
.html counter
<button type="button" (click)="increment()">Counter</button>
<br>
<h1>Counter: {{ counter }}</h1>
.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrl: './counter.component.css'
})
export class CounterComponent {
counter: number = 0;
increment() {
this.counter += 1;
}
}
This will give you a basic counter that updates every time the user clicks the button.
.html simpleform
<form (ngSubmit)="onSubmit()" #userForm="ngForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" [(ngModel)]="userData.name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" [(ngModel)]="userData.email" required>
<br><br>
<button type="submit" [disabled]="!userForm.form.valid">Submit</button>
</form>
<h2 *ngIf="submitted">Submitted Data:</h2>
<ul *ngIf="submitted">
<li><strong>Name:</strong> {{ submittedData.name }}</li>
<li><strong>Email:</strong> {{ submittedData.email }}</li>
</ul>
Create a simple form using only essential HTML elements, such as input
fields and a button
.
.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-simpleform',
templateUrl: './simpleform.component.html',
styleUrl: './simpleform.component.css'
})
export class SimpleformComponent {
userData = {
name: '',
email: ''
};
submittedData = {
name: '',
email: ''
};
submitted: boolean = false;
onSubmit() {
this.submittedData = { ...this.userData };
this.submitted = true;
}
}
Define a model to hold the input data and a method to handle form submission.
userage
.html
<label for="birthYear">Enter your birth year:</label>
<input type="number" id="birthYear" [(ngModel)]="birthYear" placeholder="">
<br><br>
<button (click)="calculateAge()">Submit</button>
<h2>Your age is: {{ age }}</h2>
Create an input field for the birth year and a button to trigger the age calculation.
.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-userage',
templateUrl: './userage.component.html',
styleUrl: './userage.component.css'
})
export class UserageComponent {
birthYear: number | null = null;
age: number = 0;
calculateAge() {
if (this.birthYear) {
const currentYear = new Date().getFullYear();
this.age = currentYear - this.birthYear;
}
}
}
Define a variable for the birth year and a method to calculate the age.
usergreeting
<label for="userName">Enter your name:</label>
<input type="text" id="userName" [(ngModel)]="userName" placeholder="Your name">
<br><br>
<button (click)="displayGreeting()">Submit</button>
<h2>{{ greeting }}</h2>
Create an input field for the user's name and a button to trigger the greeting display.
import { Component } from '@angular/core';
@Component({
selector: 'app-usergreeting',
templateUrl: './usergreeting.component.html',
styleUrl: './usergreeting.component.css'
})
export class UsergreetingComponent {
userName: string = '';
greeting: string = '';
displayGreeting() {
this.greeting = `Hello, ${this.userName}!`;
}
}
Define a variable for the user's name and a method to generate the greeting.
calculator
<label for="number1">Enter first number:</label>
<input type="number" id="number1" [(ngModel)]="number1">
<br><br>
<label for="number2">Enter second number:</label>
<input type="number" id="number2" [(ngModel)]="number2">
<br><br>
<button (click)="calculate('add')">Add</button>
<button (click)="calculate('subtract')">Subtract</button>
<button (click)="calculate('multiply')">Multiply</button>
<button (click)="calculate('divide')">Divide</button>
<br><br>
<h2>Result: {{ result }}</h2>
Create input fields for the two numbers and buttons for each operation.
import { Component } from '@angular/core';
@Component({
selector: 'app-calculator',
templateUrl: './calculator.component.html',
styleUrl: './calculator.component.css'
})
export class CalculatorComponent {
number1: number | null = null;
number2: number | null = null;
result: number | string | null = null;
calculate(operation: string) {
if (this.number1 !== null && this.number2 !== null) {
switch (operation) {
case 'add':
this.result = this.number1 + this.number2;
break;
case 'subtract':
this.result = this.number1 - this.number2;
break;
case 'multiply':
this.result = this.number1 * this.number2;
break;
case 'divide':
if (this.number2 === 0) {
this.result = 'Cannot divide by zero';
} else {
this.result = this.number1 / this.number2;
}
break;
}
} else {
this.result = 'Please enter both numbers';
}
}
}
Define variables for the two input numbers and a method to handle each operation.
textlength
<label for="inputString">Enter a string:</label>
<input type="text" id="inputString" [(ngModel)]="inputString" placeholder="Type here">
<br><br>
<button (click)="calculateLength()">Calculate Length</button>
<br><br>
<h2>Length of the string: {{ length }}</h2>
Create an input field for the user to type a string and a button to trigger the length calculation
import { Component } from '@angular/core';
@Component({
selector: 'app-textlength',
templateUrl: './textlength.component.html',
styleUrl: './textlength.component.css'
})
export class TextlengthComponent {
inputString: string = '';
length: number | null = null;
calculateLength() {
this.length = this.inputString.length;
}
}
Define a variable for the input string and a method to calculate and display the string's length.
currencyconverter
To create a simple Angular currency converter where the user inputs a value in one currency (e.g., USD) and converts it to another currency (e.g., PHP) using a fixed exchange rate (1 USD = 56 PHP), follow these steps:
<input type="number" [(ngModel)]="amount" placeholder="Input USD Amount">
<br><br>
<button (click)="convertCurrency()">Convert to PHP</button>
<br><br>
<h2>Amount in PHP: {{ convertedAmount }}</h2>
Create an input field for the user to input a value in USD and a button to trigger the conversion
import { Component } from '@angular/core';
@Component({
selector: 'app-currencyconverter',
templateUrl: './currencyconverter.component.html',
styleUrl: './currencyconverter.component.css'
})
export class CurrencyconverterComponent {
amount: number | null = null;
convertedAmount: number | null = null;
exchangeRate: number = 56;
convertCurrency() {
if (this.amount !== null) {
this.convertedAmount = this.amount * this.exchangeRate;
}
}
}
Define a variable for the input amount and a method to perform the currency conversion.
evenoddchecker
To create an Angular component that takes a number input and checks whether it is even or odd, follow these steps:
<input type="number" [(ngModel)]="number" placeholder="Enter a number">
<br><br>
<button (click)="checkEvenOrOdd()">Check</button>
<br><br>
<h2>{{ result }}</h2>
Create an input field for the user to enter a number and a button to trigger the even/odd check.
import { Component } from '@angular/core';
@Component({
selector: 'app-evenoddchecker',
templateUrl: './evenoddchecker.component.html',
styleUrl: './evenoddchecker.component.css'
})
export class EvenoddcheckerComponent {
number: number | null = null;
result: string | null = null;
checkEvenOrOdd() {
if (this.number !== null) {
if (this.number % 2 === 0) {
this.result = 'The number is even.';
} else {
this.result = 'The number is odd.';
}
} else {
this.result = 'Please enter a number.';
}
}
}
Define a variable for the input number and a method to check if it is even or odd.
wordreverser
To create an Angular component where the user inputs a word and displays the reversed word when the button is clicked, follow these steps:
<input type="text" [(ngModel)]="word" placeholder="Enter a word">
<br><br>
<button (click)="reverseWord()">Reverse</button>
<br><br>
<h2>{{ reversedWord }}</h2>
Create an input field for the user to input a word and a button to trigger the word reversal.
import { Component } from '@angular/core';
@Component({
selector: 'app-wordreverser',
templateUrl: './wordreverser.component.html',
styleUrl: './wordreverser.component.css'
})
export class WordreverserComponent {
word: string = '';
reversedWord: string = '';
reverseWord() {
this.reversedWord = this.word.split('').reverse().join('');
}
}
Define a variable for the input word and a method to reverse the word.
showdate
To create an Angular component with a button that displays the current date and time when clicked, follow these steps:
<button (click)="showDateTime()">Show Date and Time</button>
<br><br>
<h2>{{ dateTime }}</h2>
Create a button to trigger the date and time display and a paragraph to show the result.
import { Component } from '@angular/core';
@Component({
selector: 'app-showdate',
templateUrl: './showdate.component.html',
styleUrl: './showdate.component.css'
})
export class ShowdateComponent {
dateTime: string = '';
showDateTime() {
const now = new Date();
this.dateTime = now.toLocaleString();
}
}
Define a variable to hold the current date and time and a method to update this variable.
showusername
To create an Angular component where a user inputs their username and it is displayed on the screen when a button is clicked, follow these steps:
<input type="text" [(ngModel)]="username" placeholder="Enter username">
<br><br>
<button (click)="displayUsername()">Display Username</button>
<br><br>
<h2>{{ displayedUsername }}</h2>
Create an input field for the username and a button to trigger the display.
import { Component } from '@angular/core';
@Component({
selector: 'app-showusername',
templateUrl: './showusername.component.html',
styleUrl: './showusername.component.css'
})
export class ShowusernameComponent {
username: string = '';
displayedUsername: string = '';
displayUsername() {
this.displayedUsername = this.username;
}
}
Define a variable for the username and a method to display it.
multiplicationtable
To create an Angular component that takes a number input and generates its multiplication table, follow these steps:
<label for="numberInput">Enter a number:</label>
<input type="number" id="numberInput" [(ngModel)]="number" placeholder="Enter a number">
<br><br>
<button (click)="generateTable()">Generate Multiplication Table</button>
<br><br>
<ul>
<li *ngFor="let row of multiplicationTable">{{ row }}</li>
</ul>
Create an input field for the user to enter a number and a button to generate the multiplication table.
import { Component } from '@angular/core';
@Component({
selector: 'app-multiplicationtable',
templateUrl: './multiplicationtable.component.html',
styleUrls: ['./multiplicationtable.component.css']
})
export class MultiplicationtableComponent {
number: number = 0;
multiplicationTable: string[] = [];
generateTable() {
if (this.number !== null) {
this.multiplicationTable = [];
for (let i = 1; i <= 10; i++) {
this.multiplicationTable.push(`${this.number} x ${i} = ${this.number * i}`);
}
}
}
}
Define a variable for the input number and an array to hold the multiplication table.
simplelogin
To create a simple login form in Angular with email and password fields, follow these steps:
<input type="email" [(ngModel)]="email" placeholder="Enter your email" required/>
<br>
<br>
<input type="password" [(ngModel)]="password" placeholder="Enter your password" required/>
<br>
<br>
<button (click)="login()">Login</button>
<br>
<br>
<h4>{{loginmessage}}</h4>
Create a input fields for the email and password, and a button to submit the form.
import { Component } from '@angular/core';
@Component({
selector: 'app-simplelogin',
templateUrl: './simplelogin.component.html',
styleUrl: './simplelogin.component.css'
})
export class SimpleloginComponent {
email: string = '';
password: string = '';
loginmessage: string = '';
login() {
if (this.email === 'kaysie@gmail.com' && this.password === '12345') {
this.loginmessage = 'Login Successful';
} else {
this.loginmessage = 'Login Failed';
}
}
}
Define variables for the email and password and a method to handle the login action.
fahrenheittocelsius
To create an Angular component that converts temperature from Fahrenheit to Celsius based on user input, follow these steps:
<input type="number" [(ngModel)]="fahrenheit" placeholder="Enter Fahrenheit"/>
<br>
<br>
<button (click)="convertToCelsius()">Convert</button>
<h2>{{ fahrenheit }}°F is {{ celsius | number: '1.0-2' }}°C</h2>
Create an input field for the user to enter a temperature in Fahrenheit and a button to perform the conversion.
import { Component } from '@angular/core';
@Component({
selector: 'app-fahrenheittocelsius',
templateUrl: './fahrenheittocelsius.component.html',
styleUrl: './fahrenheittocelsius.component.css'
})
export class FahrenheittocelsiusComponent {
fahrenheit: number | null = null;
celsius: number | null = null;
convertToCelsius() {
if (this.fahrenheit !== null) {
this.celsius = (this.fahrenheit - 32) * 5 / 9;
} else {
this.celsius = null;
}
}
}
Define a variable for the input temperature in Fahrenheit and another variable for the converted temperature in Celsius.
bookmarklist
To create an Angular component that allows users to input URLs and display them as clickable anchor tags, follow these steps:
<input type="url" [(ngModel)]="url" placeholder="Enter a URL" />
<br>
<br>
<button (click)="addUrl()">Add URL</button>
<h2 *ngIf="urls.length > 0">URLs:</h2>
<ul *ngIf="urls.length > 0">
<li *ngFor="let url of urls">
<a [href]="url" target="_blank">{{ url }}</a>
</li>
</ul>
Create an input field for the user to enter a URL and a button to add it to the list.
import { Component } from '@angular/core';
@Component({
selector: 'app-bookmarklist',
templateUrl: './bookmarklist.component.html',
styleUrl: './bookmarklist.component.css'
})
export class BookmarklistComponent {
url: string = '';
urls: string[] = [];
addUrl() {
if (this.url) {
this.urls.push(this.url);
this.url = '';
}
}
}
Define a variable for the input URL and an array to store the list of URLs.
charactercounter
To create an Angular component that allows users to input a string and count the number of characters in it, follow these steps:
<input type="text" [(ngModel)]="inputString" placeholder="Enter a string" />
<br><br>
<button (click)="countCharacters()">Count Characters</button>
<p>Number of characters: {{ characterCount }}</p>
Create an input field for the user to enter a string and a button to trigger the character count.
import { Component } from '@angular/core';
@Component({
selector: 'app-charactercounter',
templateUrl: './charactercounter.component.html',
styleUrl: './charactercounter.component.css'
})
export class CharactercounterComponent {
inputString: string = '';
characterCount: number | null = null;
countCharacters() {
this.characterCount = this.inputString.length;
}
}
Define a variable for the input string and another variable to store the character count.
palindromechecker
To create an Angular component that allows users to input a word and check if it's a palindrome, follow these steps:
<input type="text" [(ngModel)]="inputWord" placeholder="Enter a word" />
<br><br>
<button (click)="checkPalindrome()">Check Palindrome</button>
<p>The word "{{ inputWord }}" is {{ isPalindrome ? 'a palindrome' : 'not a palindrome' }}.</p>
Create an input field for the user to enter a word and a button to trigger the palindrome check
import { Component } from '@angular/core';
@Component({
selector: 'app-palindromechecker',
templateUrl: './palindromechecker.component.html',
styleUrl: './palindromechecker.component.css'
})
export class PalindromecheckerComponent {
inputWord: string = '';
isPalindrome: boolean | null = null;
checkPalindrome() {
const cleanedWord = this.inputWord.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
const reversedWord = cleanedWord.split('').reverse().join('');
this.isPalindrome = cleanedWord === reversedWord;
}
}
Define a variable for the input word and a method to check if it's a palindrome.
temperatureconverter
To create an Angular component that allows users to convert temperatures between Celsius and Fahrenheit, follow these steps
<input type="number" [(ngModel)]="celsius" placeholder="Celsius" (ngModelChange)="convertToFahrenheit()" />
<input type="number" [(ngModel)]="fahrenheit" placeholder="Fahrenheit" (ngModelChange)="convertToCelsius()" />
<p>{{ celsius }}°C is {{ fahrenheit }}°F and {{ fahrenheit }}°F is {{ celsius }}°C</p>
Create input fields for both Celsius and Fahrenheit, along with buttons to perform the conversion
import { Component } from '@angular/core';
@Component({
selector: 'app-temperatureconverter',
templateUrl: './temperatureconverter.component.html',
styleUrl: './temperatureconverter.component.css'
})
export class TemperatureconverterComponent {
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;
}
}
}
Define variables for both Celsius and Fahrenheit temperatures, along with methods for conversion.
shoppinglist
To create a shopping list component in Angular where users can add and remove items using a list data structure, follow these steps
<input type="text" [(ngModel)]="newItem" placeholder="Add a new item" />
<br><br>
<button (click)="addItem()">Add Item</button>
<ul>
<li *ngFor="let item of items; let i = index">
{{ item }}
<button (click)="removeItem(i)">Remove</button>
</li>
</ul>
Create an input field for the user to enter an item and buttons to add and remove items
import { Component } from '@angular/core';
@Component({
selector: 'app-shoppinglist',
templateUrl: './shoppinglist.component.html',
styleUrl: './shoppinglist.component.css'
})
export class ShoppinglistComponent {
newItem: string = '';
items: string[] = [];
addItem() {
if (this.newItem.trim()) {
this.items.push(this.newItem.trim());
this.newItem = ''; // Clear input field after adding
}
}
removeItem(index: number) {
this.items.splice(index, 1); // Remove item at the specified index
}
}
Define variables for the input item and an array to store the shopping list items.
factorialcalculator
To create an Angular component that calculates the factorial of a number when a button is clicked, follow these steps:
<input type="number" [(ngModel)]="number" placeholder="Enter a number" />
<br><br>
<button (click)="calculateFactorial()">Calculate Factorial</button>
<p>The factorial of {{ number }} is {{ factorial }}.</p>
Create an input field for the user to enter a number and a button to calculate the factorial
import { Component } from '@angular/core';
@Component({
selector: 'app-factorialcalculator',
templateUrl: './factorialcalculator.component.html',
styleUrl: './factorialcalculator.component.css'
})
export class FactorialcalculatorComponent {
number: number | null = null;
factorial: number | null = null;
calculateFactorial() {
if (this.number !== null && this.number >= 0) {
this.factorial = this.computeFactorial(this.number);
} else {
this.factorial = null;
}
}
private computeFactorial(n: number): number {
if (n === 0 || n === 1) {
return 1;
}
return n * this.computeFactorial(n - 1);
}
}
Define a variable for the input number and another variable to store the factorial result.
todomanager
To create a simple to-do list component in Angular where users can add and remove tasks using a list data structure, follow these steps:
<input type="text" [(ngModel)]="newTask" placeholder="Enter a new task" />
<br><br>
<button (click)="addTask()">Add Task</button>
<ul>
<li *ngFor="let task of tasks; let i = index">
{{ task }}
<button (click)="removeTask(i)">Remove</button>
</li>
</ul>
Create an input field for the user to enter a task and buttons to add and remove tasks.
import { Component } from '@angular/core';
@Component({
selector: 'app-todomanager',
templateUrl: './todomanager.component.html',
styleUrl: './todomanager.component.css'
})
export class TodomanagerComponent {
newTask: string = '';
tasks: string[] = [];
addTask() {
if (this.newTask.trim()) {
this.tasks.push(this.newTask.trim());
this.newTask = '';
}
}
removeTask(index: number) {
this.tasks.splice(index, 1);
}
}
Define variables for the input task and an array to store the tasks.
guessnumbergame
To create a simple number guessing game in Angular where the user inputs guesses, follow these steps:
<input type="number" [(ngModel)]="userGuess" placeholder="Enter your guess" />
<br><br>
<button (click)="checkGuess()">Submit Guess</button>
<p>{{ message }}</p>
Create an input field for the user to enter their guess and buttons to check the guess and reset the game
import { Component } from '@angular/core';
@Component({
selector: 'app-guessnumbergame',
templateUrl: './guessnumbergame.component.html',
styleUrl: './guessnumbergame.component.css'
})
export class GuessnumbergameComponent {
userGuess: number | null = null;
randomNumber: number = 0;
message: string = '';
ngOnInit() {
this.generateRandomNumber();
}
generateRandomNumber() {
this.randomNumber = Math.floor(Math.random() * 100) + 1;
}
checkGuess() {
if (this.userGuess === null) {
this.message = 'Please enter a number!';
} else if (this.userGuess < this.randomNumber) {
this.message = 'Too low! Try again.';
} else if (this.userGuess > this.randomNumber) {
this.message = 'Too high! Try again.';
} else {
this.message = `Congratulations! ${this.userGuess} is the correct guess!`;
this.generateRandomNumber();
}
this.userGuess = null;
}
}
Define variables for the target number, the user's guess, and the game status.
wordcounter
To create an Angular component that counts the number of words in a given string, follow these steps:
<input type="text" [(ngModel)]="inputString" placeholder="Enter a sentence" />
<br><br>
<button (click)="countWords()">Count Words</button>
<p>Number of words: {{ wordCount }} </p>
Create an input field for the user to enter a string and a button to count the words.
import { Component } from '@angular/core';
@Component({
selector: 'app-wordcounter',
templateUrl: './wordcounter.component.html',
styleUrl: './wordcounter.component.css'
})
export class WordcounterComponent {
inputString: string = '';
wordCount: number | null = null;
countWords() {
if (this.inputString.trim()) {
this.wordCount = this.inputString.trim().split(/\s+/).length;
} else {
this.wordCount = 0;
}
}
}
Define variables for the input string and the word count.
randomnumbergenerator
To create an Angular component that generates and displays a random number between a specified range when a button is clicked, follow these steps:
<input type="number" [(ngModel)]="min" placeholder="Enter minimum value" />
<br><br>
<input type="number" [(ngModel)]="max" placeholder="Enter maximum value" />
<br><br>
<button (click)="generateRandomNumber()">Generate Random Number</button>
<p>Random number: {{ randomNumber }}</p>
Create input fields for the user to specify the minimum and maximum values, and a button to generate the random number.
import { Component } from '@angular/core';
@Component({
selector: 'app-randomnumbergenerator',
templateUrl: './randomnumbergenerator.component.html',
styleUrl: './randomnumbergenerator.component.css'
})
export class RandomnumbergeneratorComponent {
min: number | null = null;
max: number | null = null;
randomNumber: number | null = null;
generateRandomNumber() {
if (this.min !== null && this.max !== null && this.min <= this.max) {
this.randomNumber = Math.floor(Math.random() * (this.max - this.min + 1)) + this.min;
} else {
this.randomNumber = null;
}
}
}
Define variables for the minimum and maximum range, as well as the generated random number.
multiplicationchecker
To create an Angular component that checks if one number is a multiple of another, follow these steps:
<input type="number" [(ngModel)]="number" placeholder="Enter the first number" />
<br><br>
<input type="number" [(ngModel)]="divisor" placeholder="Enter the second number" />
<br><br>
<button (click)="checkMultiple()">Check if Multiple</button>
<p>{{ message }}</p>
Create input fields for the user to enter the two numbers and a button to check if one is a multiple of the other.
import { Component } from '@angular/core';
@Component({
selector: 'app-multiplicationchecker',
templateUrl: './multiplicationchecker.component.html',
styleUrl: './multiplicationchecker.component.css'
})
export class MultiplicationcheckerComponent {
number: number | null = null;
divisor: number | null = null;
message: string = '';
checkMultiple() {
if (this.number !== null && this.divisor !== null) {
if (this.divisor === 0) {
this.message = 'Cannot divide by zero.';
} else if (this.number % this.divisor === 0) {
this.message = `${this.number} is a multiple of ${this.divisor}.`;
} else {
this.message = `${this.number} is not a multiple of ${this.divisor}.`;
}
} else {
this.message = 'Please enter both numbers.';
}
}
}
Define variables for the two numbers and a result message.
uppercaseconverter
To create an Angular component that converts a string to uppercase when a button is clicked, follow these steps
<input type="text" [(ngModel)]="inputString" placeholder="Enter a string" />
<br><br>
<button (click)="convertToUppercase()">Convert to Uppercase</button>
<p>Uppercase: {{ uppercaseString }}</p>
Create an input field for the user to enter a string and a button to convert it to uppercase.
import { Component } from '@angular/core';
@Component({
selector: 'app-uppercase-converter',
templateUrl: './uppercase-converter.component.html',
})
export class UppercaseConverterComponent {
inputString: string = '';
uppercasedString: string = '';
convertToUppercase() {
this.uppercasedString = this.inputString.toUpperCase();
}
}
Define a variable for the input string and another for the uppercase result.
wordshuffler
To create an Angular component that shuffles the letters of a given word randomly, follow these steps
<input type="text" [(ngModel)]="inputWord" placeholder="Enter a word" />
<br><br>
<button (click)="shuffleLetters()">Shuffle Letters</button>
<p>Shuffled Word: {{ shuffledWord }}</p>
Create an input field for the user to enter a word and a button to shuffle its letter
import { Component } from '@angular/core';
@Component({
selector: 'app-wordshuffler',
templateUrl: './wordshuffler.component.html',
styleUrl: './wordshuffler.component.css'
})
export class WordshufflerComponent {
inputWord: string = '';
shuffledWord: string = '';
shuffleLetters() {
this.shuffledWord = this.shuffleString(this.inputWord);
}
shuffleString(word: string): string {
const array = word.split('');
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array.join('');
}
}
Define a variable for the input word and another for the shuffled result.
bmisolver
To create an Angular component that calculates and displays the Body Mass Index (BMI) based on user input for height and weight, follow these steps
<input type="number" [(ngModel)]="weight" placeholder="Enter your weight (kg)" />
<br><br>
<input type="number" [(ngModel)]="height" placeholder="Enter your height (cm)" />
<br><br>
<button (click)="calculateBMI()">Calculate BMI</button>
<p *ngIf="bmi !== null">Your BMI: {{ bmi.toFixed(2) }}</p>
<p>You are: {{ bmiCategory }}</p>
Create input fields for height and weight, and a button to calculate the BMI
import { Component } from '@angular/core';
@Component({
selector: 'app-bmisolver',
templateUrl: './bmisolver.component.html',
styleUrl: './bmisolver.component.css'
})
export class BmisolverComponent {
weight: number | null = null;
height: number | null = null;
bmi: number | null = null;
bmiCategory: string = '';
calculateBMI() {
if (this.weight !== null && this.height !== null && this.height > 0) {
const heightInMeters = this.height / 100;
this.bmi = this.weight / (heightInMeters * heightInMeters);
this.bmiCategory = this.getBMICategory(this.bmi);
} else {
this.bmi = null;
this.bmiCategory = '';
}
}
getBMICategory(bmi: number): string {
if (bmi < 18.5) {
return 'Underweight';
} else if (bmi >= 18.5 && bmi < 24.9) {
return 'Normal weight';
} else if (bmi >= 25 && bmi < 29.9) {
return 'Overweight';
} else {
return 'Obesity';
}
}
}
Define variables for height, weight, and the calculated BMI.
usernamevalidator
To create an Angular component that checks the validity of a username based on predefined rules, follow these steps. Let's assume the rules are as follows:
<input type="text" [(ngModel)]="username" placeholder="Enter a username" />
<br><br>
<button (click)="checkUsername()">Check Username</button>
<p>{{ message }}</p>
Create an input field for the user to enter a username and a button to check its validity
import { Component } from '@angular/core';
@Component({
selector: 'app-usernamevalidator',
templateUrl: './usernamevalidator.component.html',
styleUrl: './usernamevalidator.component.css'
})
export class UsernamevalidatorComponent {
username: string = '';
message: string = '';
checkUsername() {
if (!this.isValidUsername(this.username)) {
this.message = 'Invalid username. It must be at least 5 characters long, contain only alphanumeric characters, and have no spaces.';
} else {
this.message = 'Valid username!';
}
}
isValidUsername(username: string): boolean {
const minLength = 5;
const usernameRegex = /^[a-zA-Z0-9]+$/;
return username.length >= minLength && usernameRegex.test(username);
}
}
Define a variable for the username and a message for validation feedback.
interestcalculator
To create an Angular component that calculates simple interest based on user inputs for principal, rate, and time, follow these steps:
<input type="number" [(ngModel)]="principal" placeholder="Enter principal amount (P)" />
<br><br>
<input type="number" [(ngModel)]="rate" placeholder="Enter rate of interest (R)" />
<br><br>
<input type="number" [(ngModel)]="time" placeholder="Enter time (T) in years" />
<br><br>
<button (click)="calculateInterest()">Calculate Simple Interest</button>
<p>Simple Interest: {{ simpleInterest }}</p>
Create input fields for principal, rate, and time, and a button to 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;
simpleInterest: number | null = null;
calculateInterest() {
if (this.principal !== null && this.rate !== null && this.time !== null) {
this.simpleInterest = (this.principal * this.rate * this.time) / 100;
} else {
this.simpleInterest = null;
}
}
}
Define variables for the principal, rate, time, and the calculated interest.
compoundinterestcalculator
To create an Angular component that calculates compound interest based on user inputs for principal, rate, time, and frequency, follow these steps:
<input type="number" [(ngModel)]="principal" placeholder="Enter principal amount (P)" />
<br><br>
<input type="number" [(ngModel)]="rate" placeholder="Enter rate of interest (R)" />
<br><br>
<input type="number" [(ngModel)]="time" placeholder="Enter time (T) in years" />
<br><br>
<input type="number" [(ngModel)]="frequency" placeholder="Enter number of times interest is compounded per year (n)" />
<br><br>
<button (click)="calculateCompoundInterest()">Calculate Compound Interest</button>
<p *ngIf="compoundInterest !== null">Compound Interest: {{ compoundInterest.toFixed(2) }}</p>
<p *ngIf="amount !== null">Total Amount (A): {{ amount.toFixed(2) }}</p>
Create input fields for principal, rate, time, and frequency, and a button to calculate compound interest.
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;
amount: number | null = null;
calculateCompoundInterest() {
if (this.principal !== null && this.rate !== null && this.time !== null && this.frequency !== null) {
const ratePerPeriod = this.rate / (this.frequency * 100);
const totalPeriods = this.frequency * this.time;
this.amount = this.principal * Math.pow((1 + ratePerPeriod), totalPeriods);
this.compoundInterest = this.amount - this.principal;
} else {
this.compoundInterest = null;
this.amount = null;
}
}
}
Define variables for the principal, rate, time, frequency, and the calculated compound interest.
fibonaccigenerator
To create an Angular component that generates and displays the first N Fibonacci numbers when a button is clicked, follow these steps:
<input type="number" [(ngModel)]="n" placeholder="Enter the value of N" />
<br><br>
<button (click)="generateFibonacci()">Generate Fibonacci</button>
<p> 0">Fibonacci Sequence: {{ fibonacciSequence.join(', ') }}</p>
Create an input field for the user to enter N and a button to generate the Fibonacci numbers.
import { Component } from '@angular/core';
@Component({
selector: 'app-fibonaccigenerator',
templateUrl: './fibonaccigenerator.component.html',
styleUrl: './fibonaccigenerator.component.css'
})
export class FibonaccigeneratorComponent {
n: number | null = null;
fibonacciSequence: number[] = [];
generateFibonacci() {
if (this.n !== null && this.n > 0) {
this.fibonacciSequence = this.getFibonacci(this.n);
} else {
this.fibonacciSequence = [];
}
}
getFibonacci(n: number): number[] {
let fib: number[] = [0, 1];
for (let i = 2; i < n; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib.slice(0, n);
}
}
Define a variable for the number of Fibonacci numbers to generate and an array to hold the results.
oddsumcalculator
To create an Angular component that calculates the sum of odd numbers up to a given number, follow these steps
<input type="number" [(ngModel)]="n" placeholder="Enter a number" />
<br><br>
<button (click)="calculateOddSum()">Calculate Sum of Odd Numbers</button>
<p>Sum of odd numbers up to {{ n }}: {{ oddSum }}</p>
Create an input field for the user to enter a number and a button to calculate the sum of odd numbers.
import { Component } from '@angular/core';
@Component({
selector: 'app-oddsumcalculator',
templateUrl: './oddsumcalculator.component.html',
styleUrl: './oddsumcalculator.component.css'
})
export class OddsumcalculatorComponent {
n: number | null = null;
oddSum: number | null = null;
calculateOddSum() {
if (this.n !== null && this.n > 0) {
this.oddSum = this.getOddSum(this.n);
} else {
this.oddSum = null;
}
}
getOddSum(n: number): number {
let sum = 0;
for (let i = 1; i <= n; i++) {
if (i % 2 !== 0) {
sum += i;
}
}
return sum;
}
}
Define a variable for the input number and another for the calculated sum.
currencyformatter
To create an Angular component that formats a number as currency (USD, PHP, and EUR) when a button is clicked, follow these steps. For the Euro conversion, let's assume a static conversion rate for simplicity.
<input type="number" [(ngModel)]="amount" placeholder="Enter amount" />
<br><br>
<select [(ngModel)]="currency" >
<option value="USD">Dollar (USD)</option>
<option value="PHP">Philippine Peso (PHP)</option>
<option value="EUR">Euro (EUR)</option>
</select>
<br><br>
<button (click)="formatCurrency()">Format as Currency</button>
<p>Formatted Amount: {{ formattedAmount }}</p>
Create an input field for the user to enter an amount and a button to format it as currency.
import { Component } from '@angular/core';
@Component({
selector: 'app-currencyformatter',
templateUrl: './currencyformatter.component.html',
styleUrl: './currencyformatter.component.css'
})
export class CurrencyformatterComponent {
amount: number | null = null;
currency: string = 'USD';
formattedAmount: string | null = null;
formatCurrency() {
if (this.amount !== null) {
switch (this.currency) {
case 'USD':
this.formattedAmount = this.convertToDollar(this.amount);
break;
case 'PHP':
this.formattedAmount = this.convertToPhp(this.amount);
break;
case 'EUR':
this.formattedAmount = this.convertToEuro(this.amount);
break;
default:
this.formattedAmount = null;
}
}
}
convertToDollar(amount: number): string {
return `$${amount.toFixed(2)}`;
}
convertToPhp(amount: number): string {
const conversionRate = 56;
const phpAmount = amount * conversionRate;
return `₱${phpAmount.toFixed(2)}`;
}
convertToEuro(amount: number): string {
const conversionRate = 0.94;
const euroAmount = amount * conversionRate;
return `€${euroAmount.toFixed(2)}`;
}
}
Define variables for the input amount, formatted currency values, and conversion rates.
randomquotedisplay
To create an Angular component that displays a random quote from a predefined list when a button is clicked, follow these steps:
<button (click)="displayRandomQuote()">Display Random Quote</button>
<p>"{{ randomQuote }}"</p>
Create a button to generate a random quote and a section to display the selected quote.
import { Component } from '@angular/core';
@Component({
selector: 'app-randomquotedisplay',
templateUrl: './randomquotedisplay.component.html',
styleUrl: './randomquotedisplay.component.css'
})
export class RandomquotedisplayComponent {
quotes: string[] = [
"Be yourself; everyone else is already taken.",
"Without music, life would be a mistake.",
"A day without laughter is a day wasted.",
"Whenever I feel the need to exercise, I lie down until it goes away.",
"No medicine cures what happiness cannot."
];
randomQuote: string | null = null;
displayRandomQuote() {
const randomIndex = Math.floor(Math.random() * this.quotes.length);
this.randomQuote = this.quotes[randomIndex];
}
}
Define a list of quotes and a variable to hold the selected quote.
uppercasegreeting
To create an Angular component that takes a user's name as input and displays it in uppercase when a button is clicked, follow these steps:
<input type="text" [(ngModel)]="name" placeholder="Enter your name" />
<br><br>
<button (click)="convertToUppercase()">Display in Uppercase</button>
<p>{{ uppercaseName }}</p>
Create an input field for the user to enter their name and a button to convert it to 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;
convertToUppercase() {
this.uppercaseName = this.name.toUpperCase();
}
}
Define a variable for the user's name and a variable for the uppercase name.
divisiblechecker
To create an Angular component that checks if the first number is divisible by the second number, follow these steps:
<input type="number" [(ngModel)]="firstNumber" placeholder="Enter the first number" />
<br><br>
<input type="number" [(ngModel)]="secondNumber" placeholder="Enter the second number" />
<br><br>
<button (click)="checkDivisibility()">Check Divisibility</button>
<p>{{ resultMessage }}</p>
Create input fields for the two numbers and a button to check divisibility.
import { Component } from '@angular/core';
@Component({
selector: 'app-divisiblechecker',
templateUrl: './divisiblechecker.component.html',
styleUrl: './divisiblechecker.component.css'
})
export class DivisiblecheckerComponent {
firstNumber: number | null = null;
secondNumber: number | null = null;
resultMessage: string | null = null;
checkDivisibility() {
if (this.firstNumber !== null && this.secondNumber !== null) {
if (this.secondNumber === 0) {
this.resultMessage = "Division by zero is not allowed.";
} else if (this.firstNumber % this.secondNumber === 0) {
this.resultMessage = `${this.firstNumber} is divisible by ${this.secondNumber}.`;
} else {
this.resultMessage = `${this.firstNumber} is not divisible by ${this.secondNumber}.`;
}
} else {
this.resultMessage = "Please enter both numbers.";
}
}
}
Define variables for the two numbers and a variable for the result of the divisibility check.
stopwatch
To create a simple stopwatch in Angular, you can follow these steps. This stopwatch will allow users to start, stop, and reset the timer.
<p>{{ elapsedTime }} seconds</p>
<button (click)="start()">Start</button>
<button (click)="stop()">Stop</button>
<button (click)="reset()">Reset</button>
Create buttons to control the stopwatch and display the elapsed time.
import { Component } from '@angular/core';
@Component({
selector: 'app-stopwatch',
templateUrl: './stopwatch.component.html',
styleUrl: './stopwatch.component.css'
})
export class StopwatchComponent {
elapsedTime: number = 0;
timer: any = null;
start() {
if (!this.timer) {
this.timer = setInterval(() => this.elapsedTime++, 1000);
}
}
stop() {
clearInterval(this.timer);
this.timer = null;
}
reset() {
this.stop();
this.elapsedTime = 0;
}
}
Define variables for the timer, interval, and methods to control the stopwatch.
countdowntimer
To create a countdown timer in Angular, follow these steps. This timer will allow users to input a duration in seconds and start the countdown.
<input type="number" [(ngModel)]="time" placeholder="Enter time in seconds">
<button (click)="startCountdown()">Start Countdown</button>
<p>{{ timeLeft }} seconds left</p>
Create input for the duration, buttons to control the timer, and a display for the remaining time.
import { Component } from '@angular/core';
@Component({
selector: 'app-countdowntimer',
templateUrl: './countdowntimer.component.html',
styleUrl: './countdowntimer.component.css'
})
export class CountdowntimerComponent {
time: number = 0;
timeLeft: number = 0;
timer: any;
startCountdown() {
this.timeLeft = this.time;
this.timer = setInterval(() => {
if (this.timeLeft > 0) {
this.timeLeft--;
} else {
clearInterval(this.timer);
}
}, 1000);
}
}
Define variables for the countdown time, interval, and methods to control the countdown.
passwordstrengthchecker
To create a password strength checker in Angular, follow these steps. This component will allow users to input a password and see its strength based on predefined criteria.
<input type="password" [(ngModel)]="password" placeholder="Enter password">
<br><br>
<button (click)="ngOnChanges()">Check</button>
<p>Password strength: {{ strength }}</p>
Create an input field for the password and a display for the strength message.
import { Component } from '@angular/core';
@Component({
selector: 'app-passwordstrengthchecker',
templateUrl: './passwordstrengthchecker.component.html',
styleUrl: './passwordstrengthchecker.component.css'
})
export class PasswordstrengthcheckerComponent {
password: string = '';
strength: string = '';
ngOnChanges() {
const length = this.password.length;
if (length < 4) {
this.strength = 'Weak';
} else if (length < 8) {
this.strength = 'Medium';
} else {
this.strength = 'Strong';
}
}
}
Define a variable for the password and a method to assess its strength.
unitconverter
<input type="number" [(ngModel)]="value" placeholder="Enter value">
<br><br>
<button (click)="convertToKm()">To Kilometers</button>
<br><br>
<button (click)="convertToMiles()">To Miles</button>
<p>Converted Value: {{ convertedValue }}</p>
Create input fields for the value and units, along with a button to perform the conversion.
import { Component } from '@angular/core';
@Component({
selector: 'app-unitconverter',
templateUrl: './unitconverter.component.html',
styleUrl: './unitconverter.component.css'
})
export class UnitconverterComponent {
value: number = 0;
convertedValue: number = 0;
convertToKm() {
this.convertedValue = this.value * 1.60934;
}
convertToMiles() {
this.convertedValue = this.value / 1.60934;
}
}
Define variables for the input value, selected units, and the converted result.
simplevoting
To create a simple voting component in Angular, follow these steps. This example will allow users to vote for options and display the vote count.
<button (click)="upvote()">Upvote</button>
<button (click)="downvote()">Downvote</button>
<p>Total Votes: {{ votes }}</p>
Create buttons for each voting option and display the vote counts.
import { Component } from '@angular/core';
@Component({
selector: 'app-simplevoting',
templateUrl: './simplevoting.component.html',
styleUrl: './simplevoting.component.css'
})
export class SimplevotingComponent {
votes: number = 0;
upvote() {
this.votes++;
}
downvote() {
this.votes--;
}
}
Define variables for the voting options and their corresponding counts.
diceroller
To create a simple dice roller in Angular, follow these steps. This example will allow users to roll a dice (1 to 6) and display the result.
<button (click)="rollDice()">Roll Dice</button>
<p>Result: {{ diceResult }}</p>
Create a button to roll the dice and display the result.
import { Component } from '@angular/core';
@Component({
selector: 'app-diceroller',
templateUrl: './diceroller.component.html',
styleUrl: './diceroller.component.css'
})
export class DicerollerComponent {
diceResult: number | null = null;
rollDice() {
this.diceResult = Math.floor(Math.random() * 6) + 1;
}
}
Define a variable for the dice result and a method to roll the dice.
randomcolor
To create a simple random color generator in Angular, follow these steps. This example will allow users to generate a random color and display it on the screen.
<button (click)="generateColor()">Generate Random Color</button>
<p [style.color]="color">Random Color: {{ color }}</p>
Create a button to generate the color and display it with a background.
import { Component } from '@angular/core';
@Component({
selector: 'app-randomcolor',
templateUrl: './randomcolor.component.html',
styleUrl: './randomcolor.component.css'
})
export class RandomcolorComponent {
color: string = '#000000';
generateColor() {
this.color = '#' + Math.floor(Math.random() * 16777215).toString(16);
}
}
Define a variable for the color and a method to generate a random color.
lettercomparison
To create a simple letter comparison tool in Angular, follow these steps. This example will allow users to input two letters and check if they are the same or different.
<input [(ngModel)]="string1" placeholder="Enter first word">
<input [(ngModel)]="string2" placeholder="Enter second word">
<button (click)="compareStrings()">Compare</button>
<p>{{ resultMessage }}</p>
Create input fields for the letters and a button to perform the comparison.
import { Component } from '@angular/core';
@Component({
selector: 'app-lettercomparison',
templateUrl: './lettercomparison.component.html',
styleUrl: './lettercomparison.component.css'
})
export class LettercomparisonComponent {
string1: string = '';
string2: string = '';
resultMessage: string = '';
compareStrings() {
this.resultMessage = this.string1 === this.string2 ? 'Strings are equal' : 'Strings are different';
}
}
Define variables for the input letters and the comparison result.
palindromenumber
To create a simple palindrome number checker in Angular, follow these steps. This example will allow users to input a number and check if it is a palindrome.
<input type="number" [(ngModel)]="number" placeholder="Enter a number">
<button (click)="checkPalindrome()">Check Palindrome</button>
<p>{{ palindromeMessage }}</p>
Create an input field for the number and a button to perform the palindrome check.
import { Component } from '@angular/core';
@Component({
selector: 'app-palindromenumber',
templateUrl: './palindromenumber.component.html',
styleUrl: './palindromenumber.component.css'
})
export class PalindromenumberComponent {
number: number = 0;
palindromeMessage: string = '';
checkPalindrome() {
const strNumber = this.number.toString();
this.palindromeMessage = strNumber === strNumber.split('').reverse().join('')
? 'It is a palindrome number'
: 'Not a palindrome number';
}
}
Define variables for the input number and the comparison result.
daysuntilbirthday
To create a simple application in Angular that calculates the number of days until the user's next birthday, follow these steps. This example will allow users to input their birthday and see how many days are left until the next occurrence.
<input type="date" [(ngModel)]="birthday" placeholder="Enter your birthday">
<button (click)="calculateDays()">Calculate Days</button>
<p>Days until your birthday: {{ daysLeft }}</p>
Create an input field for the birthday and a button to calculate the days until the next birthday.
import { Component } from '@angular/core';
@Component({
selector: 'app-daysuntilbirthday',
templateUrl: './daysuntilbirthday.component.html',
styleUrl: './daysuntilbirthday.component.css'
})
export class DaysuntilbirthdayComponent {
birthday: Date | null = null;
daysLeft: number | null = null;
calculateDays() {
if (this.birthday) {
const today = new Date();
let nextBirthday = new Date(today.getFullYear(), new Date(this.birthday).getMonth(), new Date(this.birthday).getDate());
if (nextBirthday < today) {
nextBirthday.setFullYear(today.getFullYear() + 1);
}
const differenceInTime = nextBirthday.getTime() - today.getTime();
this.daysLeft = Math.ceil(differenceInTime / (1000 * 3600 * 24));
} else {
this.daysLeft = null;
}
}
}
Define variables for the birthday input and the days until the next birthday.