The following article provides a few Basic Programs in Angular.
- Hello World Program.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<h1>Hello, World!</h1>'
})
export class AppComponent {
}
- Data Binding Program.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>{{ title }}</h1>
<p>{{ message }}</p>
`
})
export class AppComponent {
title = 'Data Binding Example';
message = 'This is an example of data binding';
}
- Event Handling Program.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<button (click)="onButtonClick()">Click me!</button>
<p *ngIf="showMessage">{{ message }}</p>
`
})
export class AppComponent {
message = 'Button clicked!';
showMessage = false;
onButtonClick() {
this.showMessage = true;
}
}
- NgFor Program.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
`
})
export class AppComponent {
items = ['Apple', 'Banana', 'Orange', 'Grape'];
}
- NgIf Program.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div *ngIf="showMessage">
<p>{{ message }}</p>
</div>
`
})
export class AppComponent {
message = 'This message will be shown if showMessage is true.';
showMessage = true;
}
- Component Communication Program.
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<h1>Parent Component</h1>
<app-child [message]="parentMessage"></app-child>
`
})
export class ParentComponent {
parentMessage = 'This message is from the parent component';
}
@Component({
selector: 'app-child',
template: `
<h2>Child Component</h2>
<p>{{ message }}</p>
`
})
export class ChildComponent {
@Input() message: string;
}
- Routing Program.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
import { ContactComponent } from './contact.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
- Form Handling Program.
pythonCopy codeimport { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
<form [formGroup]="form" (submit)="onSubmit()">
<label>
Name:
<input type="text" formControlName="name">
</label>
<label>
Email:
<input type="email" formControlName="email">
</label>
<button type="submit">Submit</button>
</form>
`
})
export class AppComponent {
form = new FormGroup({
name: new FormControl('',
Further Reading
Creating Single Page Applications with Angular
Angular 10 Data Binding in Different Ways