Angular, Typescript - rlip/java GitHub Wiki
npm -i - instaluje zgodnie z package-lock - żeby wersje były takie same
npm ci - wszystko usuwa i instaluje wszystko od nowa
ng generate component home/home --type=page //z nazwą page zamiast component
ng generate module contact --routing -d // d - to zawsze dry run
npm i @ngrx/signals@latest --force
ng g c --standalone=false --type=page contact/contact-admin
ng g component --type=dialog auth/loginng g directive directives/highlite
ng g directive directives/has-role
//
export class HasRoleDirective {
@HostBinding('style.text-decoration')
decoration = ''
@HostListener('mouseover')
mouseOver() {
this.decoration = 'underline'
}
@HostListener('mouseout')
mouseOut() {
this.decoration = ''
}
}
/////
export class HasRoleDirective {
auth = inject(AuthStore)
templateRef = inject(TemplateRef)
viewContainerRef = inject(ViewContainerRef);
constructor() {
effect(() => {
if(this.auth.user()) {
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.viewContainerRef.clear()
}
})
}
}
// podkreslenie i pojawia się tylko po zalogowaniu
<a routerLink="/contact/admin" routerLinkActive="font-bold" appHighlite *appHasRole>Admin</a> ng g pipe auth/user-photo
//
@Pipe({
name: 'userPhoto',
standalone: true
})
export class UserPhotoPipe implements PipeTransform {
transform(user: User | undefined | null, ...args: unknown[]): unknown {
if (user) {
return `https://randomuser.me/api/portraits/men/${user.id}.jpg`
}
return `https://randomuser.me/api/portraits/lego/7.jpg`;
}
}
//
<img [src]="auth.user() | userPhoto: 'jpg':'large'" class="rounded-full h-6">
- można dodać np. prebuild, postbuild, postinstall script, żeby coś odpalić przed budowaniem
...
"scripts": {
"prebuild": "pwd"
...
route = inject(ActiveRoute);
// albo
@Injext(TemplateRef)
templateRef: TemplateRef<any> | undefinied
/////
Injector.ge-t(User)
<h1 class="{{ use_dark_background ? 'darkbg' : ''}}">lorem</h1> // to samo co:
<h1 [class.darkbg]="use_dark_background">lorem</h1>
<h1 [ngClass]="current_css_classes">lorem</h1> //dodaje wszystkie klucze (jako klasy) z obiektu current_css_classes,
// jeśli wartośc dla teego kulcza to true
// [ngStyle] działa analogicznie dla stylu, ale przyjmuje wszystkie wartości np color: "red"
----------------------------------------------------
<div *ngIf="recipe.cover_photo">...</div> // jeśli nie recipe.cover_photo to nie dodaje diva do doma
----------------------------------------------------
@Input()
recipe: Recipe;
@Output
zoomIn: EventEmitter<Recipe> = new EventEmitter();
fireZoomEvent() { // tą fukcję gdzieś wywyołać w htmlu np. (click)=fireZoomEvent()
this.zoomIn.emit(this.recipe)
}
//potem gdzieś w htmlu w elemencie można dać (zoomIn)=nazwaFunkcjiDoWykonania(recipe)
// i napisać tą funkcję już w ts/js metaService = inject(Meta);
titleService = inject(Title);
// i potem
this.titleService.setTitle(contact.name);
this.metaService.removeTag('description')
this.metaService.addTag({name: 'description', content: contact.name})uruchomienie
ng servedo stylowania, nawet fajny
Mamy
- Klasy z możliwością dziedziczenia i interfejsy
//Gettery i Settery
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
}
set fullName(newName: string) {
}
if (!newName) {
}
throw new Error('empty value not allowed')
this._fullName = newName;
let employee = new Employee(); employee. fullName = "Bob Smith";
// z tablicy
const [a, b] = [1,2,3];
// z obiektu
const {rename, path, join } = require('fs')
const {one, two, three} = {one: 'vall', two: 'val2', three: 'val3'}
// parametry funkcji
function parse({name: x}) {
}
console.log(x);
parse({name: 5})- Default,...spreed, ...rest
function f(x, y = 12) {
}
// domyślna wartość y (jeśli y === == undefined) return x + y;
f(3) == === 15;
function f(x,
}
y) {
// y jest tablicą pozostałych wartości return xy.length;
f(3, "hello", true) === 6;
function f(x, y, z) {
}
return x + y + z;
// przekazanie każdego elementu tablicy osobno
f(... [1, 2, 3]) === = 6;
- Mamy:
- number
- string
- Bollean
- symbol
- null, undefinied
- any
- void // do zwracania
- Mamy typy generyczne.
- tuple - czyli tablica z zadelkarowanymi typami
- enum
enum Color {
Red, // można zrobić Red = 'R' wtedy c (niżej) będzie miało wartość 'R' a nie 1
Green,
Blue
}
let c: Color = Color.Red;- Można deklarować zmienne jako
let x: string | Boolean
let names: string | string[]- Można
class User {
private fullName: string | undefined // w javascript trzeba by deklarować w konstruktorze
// i nie ma private
}- Można też w konstuktorze podać tylko nazwę zmiennej i to czy jest np. private, a nie trzeba jesj ani deklarowac ani przypisywać jej warości
constructor(
private router: Router
) {}
- W konfiguracji
tsconfig.jsonmożemy ustalić do jakiej wersji js ma być kompilowany, ustawiamy też strict - będzie zgłaszał będy jak typ nie może być nullem anbo undefinied a jest
kompilacja:
tsc ts1.tsnode:
sudo apt install nodejs
npm:
sudo npm install --force
typescript:
sudo npm install -g typescript
angular cli
sudo npm install -g @angular/cli
create project:
ng new hello-angularls