import { Component } from '@angular/core';
@Component({
selector: 'app-hello',
template: '<h1>Hello, {{name}}!</h1>',
styles: ['h1 { font-weight: normal; }']
})
export class HelloComponent {
name: string = 'Angular';
}
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<h2>{{childTitle}}</h2>
<button (click)="sendMessage()">Send Message</button>
`
})
export class ChildComponent {
@Input() childTitle: string;
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from child!');
}
}
<h1>{{title}}</h1>
<p>Sum: {{ 1 + 1 }}</p>
<p>String manipulation: {{ title.toUpperCase() }}</p>
<img [src]="imageUrl">
<button [disabled]="isUnchanged">Disabled Button</button>
<button (click)="onSave()">Save</button>
<input (keyup.enter)="onEnter($event)">
<input [(ngModel)]="name">
<p *ngIf="condition">Conditional content</p>
<ul>
<li *ngFor="let item of items; let i = index">{{i}}: {{item}}</li>
</ul>
<div [ngSwitch]="conditionExpression">
<ng-container *ngSwitchCase="expression1">Output 1</ng-container>
<ng-container *ngSwitchCase="expression2">Output 2</ng-container>
<ng-container *ngSwitchDefault>Default output</ng-container>
</div>
<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
Styled content
</div>
<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">
Styled content
</div>
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input('appHighlight') highlightColor: string;
constructor(private el: ElementRef) {}
ngOnInit() {
this.el.nativeElement.style.backgroundColor = this.highlightColor || 'yellow';
}
}
<p>{{ dateValue | date:'short' }}</p>
<p>{{ price | currency:'USD':'symbol':'1.2-2' }}</p>
<p>{{ longText | slice:0:50 }}...</p>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent = 1): number {
return Math.pow(value, exponent);
}
}
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data: string[] = [];
addData(item: string) {
this.data.push(item);
}
getData(): string[] {
return this.data;
}
}
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-my-component',
template: '<ul><li *ngFor="let item of items">{{item}}</li></ul>'
})
export class MyComponent {
items: string[];
constructor(private dataService: DataService) {
this.items = this.dataService.getData();
}
}
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<router-outlet></router-outlet>
<a routerLink="/home">Home</a>
<a [routerLink]="['/user', userId]">User Profile</a>
<form (ngSubmit)="onSubmit()" #myForm="ngForm">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" [(ngModel)]="model.name" required>
</div>
<button type="submit" [disabled]="!myForm.form.valid">Submit</button>
</form>
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html'
})
export class ProfileEditorComponent {
profileForm: FormGroup;
constructor(private fb: FormBuilder) {
this.profileForm = this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: ['']
})
});
}
onSubmit() {
console.log(this.profileForm.value);
}
}
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getData(): Observable<any> {
return this.http.get('https://api.example.com/data');
}
}
postData(data: any): Observable<any> {
return this.http.post('https://api.example.com/data', data);
}
import { Observable } from 'rxjs';
const myObservable = new Observable(observer => {
observer.next('Hello');
observer.next('World');
observer.complete();
});
myObservable.subscribe(
value => console.log(value),
error => console.error(error),
() => console.log('Completed')
);
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
@NgModule({
imports: [CommonModule],
declarations: [FeatureComponent],
exports: [FeatureComponent]
})
export class FeatureModule { }
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-lifecycle',
template: '<p>Lifecycle Component</p>'
})
export class LifecycleComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-on-push',
template: '<p>{{data}}</p>',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {
data: string = 'Initial data';
}
import { Input, Output, EventEmitter } from '@angular/core';
export class MyComponent {
@Input() inputProperty: string;
@Output() outputEvent = new EventEmitter<string>();
}
ng new my-app
ng serve
ng generate component my-component
ng build --prod
ng test
ng lint
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MyComponent ]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-animate',
template: '<div [@openClose]="isOpen ? 'open' : 'closed'">Content</div>',
animations: [
trigger('openClose', [
state('open', style({
height: '200px',
opacity: 1,
backgroundColor: 'yellow'
})),
state('closed', style({
height: '100px',
opacity: 0.5,
backgroundColor: 'green'
})),
transition('open => closed', [
animate('1s')
]),
transition('closed => open', [
animate('0.5s')
]),
]),
],
})
export class AnimateComponent {
isOpen = true;
}
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-sanitizer',
template: '<div [innerHTML]="safeHtml"></div>'
})
export class SanitizerComponent {
safeHtml: SafeHtml;
constructor(private sanitizer: DomSanitizer) {
const unsafeHtml = '<script>alert("XSS")</script> <b>Bold text</b>';
this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(unsafeHtml);
}
}
import { TranslateService } from '@ngx-translate/core';
export class AppComponent {
constructor(private translate: TranslateService) {
translate.setDefaultLang('en');
}
useLanguage(language: string) {
this.translate.use(language);
}
}
<h1>{{ 'TITLE' | translate }}</h1>
<button (click)="useLanguage('en')">English</button>
<button (click)="useLanguage('fr')">Français</button>
const routes: Routes = [
{
path: 'customers',
loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
}
];
ng build --aot
2024 © All rights reserved - buraxta.com