Angular frontend framework utilities and components with TypeScript support, including directives, services, and window management
npm install @ts-core/angularAngular библиотека с базовыми утилитами, директивами, пайпами и сервисами для разработки веб-приложений. Предоставляет инструменты для работы с языками, темами, окнами, авторизацией, хранилищами данных и многим другим.
- Установка
- Зависимости
- Быстрый старт
- Модули
- Директивы
- Пайпы
- Сервисы
- Авторизация
- Управление окнами
- Хранилища данных
- Примеры использования
- Связанные пакеты
``bash`
npm install @ts-core/angular
`bash`
yarn add @ts-core/angular
`bash`
pnpm add @ts-core/angular
| Пакет | Описание |
|-------|----------|
| @angular/core | Angular фреймворк |@ts-core/common
| | Базовые классы и интерфейсы |@ts-core/frontend
| | Фронтенд утилиты |@ts-core/language
| | Поддержка локализации |moment
| | Работа с датами |numeral
| | Форматирование чисел |ngx-cookie
| | Работа с cookies |interactjs
| | Drag-and-drop и resize |
`typescript
import { NgModule } from '@angular/core';
import { VIModule } from '@ts-core/angular';
@NgModule({
imports: [
VIModule.forRoot({
loggerLevel: LoggerLevel.ALL,
languageOptions: {
defaultLocale: 'ru',
supportedLocales: ['ru', 'en']
},
themeOptions: {
defaultTheme: 'light',
supportedThemes: ['light', 'dark']
}
})
]
})
export class AppModule {}
`
`typescript
import { Component } from '@angular/core';
import { VIModule } from '@ts-core/angular';
@Component({
standalone: true,
imports: [VIModule]
})
export class MyComponent {}
`
Объединяет все подмодули и предоставляет базовые сервисы:
`typescript
import { VIModule, IVIOptions } from '@ts-core/angular';
const options: IVIOptions = {
loggerLevel: LoggerLevel.DEBUG,
languageOptions: {
defaultLocale: 'ru',
supportedLocales: ['ru', 'en', 'de']
},
themeOptions: {
defaultTheme: 'light',
supportedThemes: ['light', 'dark']
}
};
@NgModule({
imports: [VIModule.forRoot(options)]
})
export class AppModule {}
`
Модуль локализации:
`typescript
import { LanguageModule } from '@ts-core/angular';
@NgModule({
imports: [LanguageModule]
})
export class MyModule {}
`
Модуль тем:
`typescript
import { ThemeModule } from '@ts-core/angular';
@NgModule({
imports: [ThemeModule]
})
export class MyModule {}
`
Модуль для работы с ресурсами:
`typescript
import { AssetModule } from '@ts-core/angular';
@NgModule({
imports: [AssetModule]
})
export class MyModule {}
`
Модуль для работы с cookies:
`typescript
import { CookieModule } from '@ts-core/angular';
@NgModule({
imports: [CookieModule]
})
export class MyModule {}
`
#### FocusDirective
Автоматическая фокусировка элемента:
`html`
#### ClickToCopyDirective
Копирование текста по клику:
`html`
Кликните чтобы скопировать
{{ dynamicText }}
#### ClickToSelectDirective
Выделение текста по клику:
`html`
#### SelectOnFocusDirective
Выделение текста при фокусе:
`html`
#### InfiniteScrollDirective
Бесконечная прокрутка:
`html`
{{ item }}
#### ScrollDirective
Отслеживание прокрутки:
`html`
Контент
#### AutoScrollBottomDirective
Автопрокрутка вниз:
`html`
{{ message }}
#### ScrollCheckDirective
Проверка возможности прокрутки:
`html`
Контент
#### ResizeDirective
Отслеживание изменения размера:
`html`
Контент
`typescript`
onResize(event: { width: number; height: number }): void {
console.log('Новый размер:', event);
}
#### AspectRatioResizeDirective
Сохранение пропорций:
`html`
Видео контейнер
#### IsBrowserDirective
Отображение только в браузере:
`html`
Отображается только в браузере (не в SSR)
#### IsServerDirective
Отображение только на сервере:
`html`
Отображается только на сервере (SSR)
#### NullEmptyValueDirective
Преобразование пустой строки в null:
`html`
#### UppercaseValueDirective
Автоматический uppercase:
`html`
#### HTMLTitleDirective
Установка заголовка страницы:
`html`
#### HTMLContentTitleDirective
Установка заголовка из контента элемента:
`html`Заголовок страницы
#### MomentDatePipe
`html`
{{ date | viMomentDate }}
{{ date | viMomentDate:'DD.MM.YYYY' }}
{{ date | viMomentDate:'DD MMMM YYYY':'ru' }}
#### MomentTimePipe
`html`
{{ date | viMomentTime }}
{{ date | viMomentTime:'HH:mm:ss' }}
#### MomentDateFromNowPipe
`html`
{{ date | viMomentDateFromNow }}
#### MomentDateAdaptivePipe
`html`
{{ date | viMomentDateAdaptive }}
#### FinancePipe
`html
{{ 1234567.89 | viFinance }}
{{ 1234567.89 | viFinance:'0,0.00' }}
`
#### TimePipe
`html
{{ 3661 | viTime }}
{{ 125 | viTime }}
`
#### TruncatePipe
`html`
{{ longText | viTruncate:50 }}
{{ longText | viTruncate:50:'...' }}
#### CamelCasePipe
`html`
{{ 'hello world' | viCamelCase }}
#### StartCasePipe
`html`
{{ 'hello world' | viStartCase }}
#### SanitizePipe
`html`
Ссылка
#### PrettifyPipe
`html`{{ jsonObject | viPrettify }}
#### NgModelErrorPipe
`html`
{{ form.controls.email.errors | viNgModelError }}
Абстрактный сервис для управления окнами:
`typescript
import { WindowService, IWindowConfig } from '@ts-core/angular';
@Component({...})
export class MyComponent {
constructor(private windowService: WindowService) {}
openDialog(): void {
const content = this.windowService.open(MyDialogComponent, {
data: { message: 'Hello!' },
width: '400px'
});
content.events.subscribe(event => {
console.log('Window event:', event);
});
}
showInfo(): void {
this.windowService.info('info.message');
}
askQuestion(): void {
const question = this.windowService.question('confirm.delete');
question.yesClick.subscribe(() => {
console.log('Подтверждено');
});
}
}
`
Сервис уведомлений:
`typescript
import { NotificationService, NotificationConfig } from '@ts-core/angular';
@Component({...})
export class MyComponent {
constructor(private notifications: NotificationService) {}
showNotification(): void {
this.notifications.show({
message: 'Операция выполнена успешно',
type: 'success',
duration: 3000
});
}
}
`
Сервис нижних листов:
`typescript
import { BottomSheetService } from '@ts-core/angular';
@Component({...})
export class MyComponent {
constructor(private bottomSheet: BottomSheetService) {}
openSheet(): void {
this.bottomSheet.open(MySheetComponent, {
data: { items: this.items }
});
}
}
`
Работа с cookies:
`typescript
import { CookieService } from '@ts-core/angular';
@Component({...})
export class MyComponent {
constructor(private cookies: CookieService) {}
setCookie(): void {
this.cookies.put('token', 'value', {
expires: new Date(Date.now() + 86400000),
path: '/'
});
}
getCookie(): string {
return this.cookies.get('token');
}
removeCookie(): void {
this.cookies.remove('token');
}
}
`
Работа с localStorage:
`typescript
import { LocalStorageService } from '@ts-core/angular';
@Component({...})
export class MyComponent {
constructor(private storage: LocalStorageService) {}
saveData(): void {
this.storage.setItem('key', 'value');
}
loadData(): string {
return this.storage.getItem('key');
}
}
`
Определение платформы:
`typescript
import { PlatformService } from '@ts-core/angular';
@Component({...})
export class MyComponent {
constructor(private platform: PlatformService) {}
checkPlatform(): void {
if (this.platform.isBrowser) {
// Код для браузера
}
if (this.platform.isServer) {
// Код для SSR
}
}
}
`
Управление фокусом:
`typescript
import { FocusManager } from '@ts-core/angular';
@Component({...})
export class MyComponent {
constructor(private focusManager: FocusManager) {}
focusElement(): void {
this.focusManager.focus(this.inputElement);
}
}
`
Отслеживание изменения размера окна:
`typescript
import { ResizeManager } from '@ts-core/angular';
@Component({...})
export class MyComponent implements OnInit {
constructor(private resizeManager: ResizeManager) {}
ngOnInit(): void {
this.resizeManager.events.subscribe(event => {
console.log('Window resized:', event);
});
}
}
`
Базовый класс для сервиса авторизации:
`typescript
import { LoginServiceBase, LoginServiceBaseEvent } from '@ts-core/angular';
@Injectable({ providedIn: 'root' })
export class AuthService extends LoginServiceBase
constructor(private http: HttpClient) {
super();
}
// Реализация абстрактных методов
protected async loginRequest(credentials: LoginCredentials): Promise
return this.http.post
}
protected async loginSidRequest(): Promise
return this.http.get
}
protected async logoutRequest(): Promise
await this.http.post('/api/auth/logout', {}).toPromise();
}
protected getSavedSid(): string {
return localStorage.getItem('sid');
}
protected parseLoginResponse(response: LoginResponse): void {
this._sid = response.token;
localStorage.setItem('sid', response.token);
}
// Публичный метод входа
public login(credentials: LoginCredentials): void {
this.loginByParam(credentials);
}
}
`
`typescript
@Component({...})
export class LoginComponent {
constructor(private auth: AuthService) {
// Подписка на события
this.auth.logined.subscribe(userData => {
console.log('Пользователь вошёл:', userData);
});
this.auth.logouted.subscribe(() => {
console.log('Пользователь вышел');
});
}
login(): void {
this.auth.login({ email: 'user@example.com', password: '123' });
}
logout(): void {
this.auth.logout();
}
get isLoggedIn(): boolean {
return this.auth.isLoggedIn;
}
}
`
Защита маршрутов:
`typescript
import { LoginGuard, LoginNotGuard, LoginIfCanGuard } from '@ts-core/angular';
const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [LoginGuard] // Только для авторизованных
},
{
path: 'login',
component: LoginComponent,
canActivate: [LoginNotGuard] // Только для неавторизованных
},
{
path: 'profile',
component: ProfileComponent,
canActivate: [LoginIfCanGuard] // Попытка авторизации если есть токен
}
];
`
Хранение токена авторизации:
`typescript
import { LoginTokenStorage } from '@ts-core/angular';
@Injectable()
export class AuthService {
constructor(private tokenStorage: LoginTokenStorage) {}
saveToken(token: string): void {
this.tokenStorage.set(token);
}
getToken(): string {
return this.tokenStorage.get();
}
clearToken(): void {
this.tokenStorage.remove();
}
}
`
Базовый класс для содержимого окна:
`typescript
import { WindowBase, IWindowContent } from '@ts-core/angular';
@Component({
template:
{{ config.data.message }}
})
export class MyWindowComponent extends WindowBase implements IWindowContent {
close(): void {
this.config.data.result = 'closed';
this.destroy();
}
}interface MyWindowData {
title: string;
message: string;
result?: string;
}
`$3
Конфигурация окна:
`typescript
import { WindowConfig, IWindowConfig } from '@ts-core/angular';const config: IWindowConfig = {
data: { title: 'Заголовок' },
width: '500px',
height: 'auto',
disableClose: false,
panelClass: 'my-dialog'
};
`$3
Управление вопросами:
`typescript
import { QuestionManager, IQuestion } from '@ts-core/angular';@Component({...})
export class MyComponent {
constructor(private questionManager: QuestionManager) {}
askConfirmation(): void {
const question = this.questionManager.question('Вы уверены?');
question.yesClick.subscribe(() => {
this.deleteItem();
});
question.noClick.subscribe(() => {
console.log('Отменено');
});
}
}
`Хранилища данных
$3
Типизированное хранилище:
`typescript
import { ValueStorage, BooleanValueStorage, DateValueStorage, JSONValueStorage } from '@ts-core/angular';// Boolean хранилище
const isDarkMode = new BooleanValueStorage(localStorage, 'darkMode', false);
isDarkMode.value = true;
console.log(isDarkMode.value); // true
// Date хранилище
const lastVisit = new DateValueStorage(localStorage, 'lastVisit');
lastVisit.value = new Date();
console.log(lastVisit.value); // Date object
// JSON хранилище
interface UserSettings {
theme: string;
language: string;
}
const settings = new JSONValueStorage(localStorage, 'settings', {
theme: 'light',
language: 'ru'
});
settings.value = { theme: 'dark', language: 'en' };
`Примеры использования
$3
`typescript
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { VIModule, IVIOptions } from '@ts-core/angular';
import { LoggerLevel } from '@ts-core/common';const viOptions: IVIOptions = {
loggerLevel: LoggerLevel.DEBUG,
languageOptions: {
defaultLocale: 'ru',
supportedLocales: ['ru', 'en', 'de'],
loadUrl: '/api/language'
},
themeOptions: {
defaultTheme: 'light',
supportedThemes: ['light', 'dark', 'auto']
}
};
@NgModule({
imports: [
BrowserModule,
VIModule.forRoot(viOptions)
],
bootstrap: [AppComponent]
})
export class AppModule {}
`$3
`typescript
import { Component } from '@angular/core';
import { LanguageService } from '@ts-core/frontend';@Component({
selector: 'app-greeting',
template:
{{ 'greeting.message' | viLanguage:{ name: userName } }}
})
export class GreetingComponent {
userName = 'Иван';
locales = ['ru', 'en', 'de'];
constructor(private language: LanguageService) {}
changeLanguage(locale: string): void {
this.language.setLocale(locale);
}
}
`
`typescript
import { Component } from '@angular/core';
import { ThemeService } from '@ts-core/frontend';
@Component({
selector: 'app-theme-toggle',
template:
})
export class ThemeToggleComponent {
constructor(private theme: ThemeService) {} get isDark(): boolean {
return this.theme.current === 'dark';
}
toggleTheme(): void {
this.theme.setTheme(this.isDark ? 'light' : 'dark');
}
}
`$3
`typescript
import { Component } from '@angular/core';@Component({
selector: 'app-infinite-list',
template:
})
export class InfiniteListComponent {
items: any[] = [];
isLoading = false;
page = 1; async loadMore(): Promise {
if (this.isLoading) return;
this.isLoading = true;
const newItems = await this.loadPage(this.page++);
this.items = [...this.items, ...newItems];
this.isLoading = false;
}
private async loadPage(page: number): Promise {
// Загрузка данных с сервера
return fetch(
/api/items?page=${page}).then(r => r.json());
}
}
`API Reference
$3
| Метод | Описание |
|-------|----------|
|
forRoot(options?) | Создать модуль с настройками |$3
| Свойство | Тип | Описание |
|----------|-----|----------|
|
loggerLevel | LoggerLevel | Уровень логирования |
| languageOptions | ILanguageServiceOptions | Настройки локализации |
| themeOptions | IThemeServiceOptions | Настройки тем |$3
| Метод | Описание |
|-------|----------|
|
open(component, config) | Открыть окно |
| get(id) | Получить окно по ID |
| has(id) | Проверить наличие окна |
| close(id) | Закрыть окно |
| closeAll() | Закрыть все окна |
| info(translationId, translation?, options?) | Показать информационное окно |
| question(translationId, translation?, options?) | Показать окно подтверждения |$3
| Свойство/Метод | Тип | Описание |
|----------------|-----|----------|
|
isLoggedIn | boolean | Авторизован ли пользователь |
| isLoading | boolean | Идёт процесс авторизации |
| sid | string | Текущий токен сессии |
| loginData | V | Данные пользователя |
| login(param) | void | Выполнить вход |
| logout() | Promise | Выполнить выход |
| logined | Observable | Событие успешного входа |
| logouted | Observable | Событие выхода |Связанные пакеты
| Пакет | Описание |
|-------|----------|
|
@ts-core/angular-material | Material компоненты для Angular |
| @ts-core/frontend | Базовые фронтенд утилиты |
| @ts-core/common | Общие классы и интерфейсы |
| @ts-core/language` | Поддержка локализации |Renat Gubaev — renat.gubaev@gmail.com
- GitHub: ManhattanDoctor
- Репозиторий: ts-core-frontend-angular
ISC