Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Aphorismen
Applications
Business Economics & Admin.
My Computers
Cooking
Devices
Folders
Food
Hardware
Infos
Software Development
Sports
Operation Instructions
Todos
Test
Help
Glossary
Community portal
adaptions
Sidebar anpassen
Wiki RB4
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Angular
Page
Discussion
English
Read
Edit
View history
Toolbox
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Concept== * [https://angular.io/ Angular Home] Angular is a platform and framework for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps. [[File:Angular.jpg|500px]] <code>[file:///C:/Uwes/owncloud/documents/Software_Development/Programming/Frameworks/Angular/Angular.drawio]</code> ===Modules=== The basic building blocks are '''NgModules''', which provide a compilation context for components and which bundles different Angular building blocks. An Angular app is defined by a set of NgModules. An app always has at least a <span id="RootModule">'''root module'''</span> conventionally named <code>AppModule</code> that enables [https://angular.io/guide/bootstrapping bootstrapping], and typically has many more '''feature modules'''. Like JavaScript modules, NgModules can import functionality from other NgModules, and allow their own functionality to be exported and used by other NgModules. For example, to use the router service in your app, you import the Router NgModule. @NgModule ===Components=== Every Angular application has at least one '''component''', the '''root''' (top level) '''component''' that connects a component hierarchy (component tree) with the page document object model (DOM). A component controls a patch of screen called a view. Each component defines a '''selector''', a class that contains application data and logic (view logic), and is associated with an HTML template that defines a view to be displayed in a target environment (see [[Angular#Own_Components|@Component]]). ====Root Component==== * see <code><APP_ROOT_DIR>\src\app.component.*</code> * change title in <code>app.component.ts</code> ====Own Components==== A component instance has a [https://angular.io/guide/lifecycle-hooks lifecycle] that starts when Angular instantiates the component class and renders the component view along with its child views. The lifecycle continues with change detection, as Angular checks to see when data-bound properties change, and updates both the view and the component instance as needed. The lifecycle ends when Angular destroys the component instance and removes its rendered template from the DOM. '''@Component({''' // from angular core '''selector:''' '<SELECTOR>', // tag name within html '''templateUrl:''' '<PATH_FILENAME>', // path and filename of the corresponding template '''template:''' '<HTML_CODE>', // e.g. <h1>{{title}}</h1> '''styleUrls:''' // the styles only apply to the component '''})''' '''export class''' <COMPONENT_CLASS> ['''implements OnInit'''] '''{''' ['''ngOnInit() {''' // is called shortly after creating a component '''}'''] '''}''' In addition each component needs to be declared in a module, normally in <code>@NgModule ... AppModule</code> Components use '''[[Angular#Services|services]]'''. ====Parent/Child Component Relation==== A parent child relation is established by using the selector of the child component in the template of the parent component. ====Templates==== The metadata for a component class associates it with a '''template''' that defines a view. A template combines ordinary HTML with Angular directives and binding markup that allow Angular to modify the HTML before rendering it for display. The metadata for a service class provides the information Angular needs to make it available to components through '''dependency injection''' (DI). {{<PROPERTY>}} // data binding to property of component class {{<OBJECT>.<PROPERTY>}} {{todo.targetDate}} | date // pipes are date, lowercase, uppercase, ... (<EVENT>)=<METHOD> // event binding [(ngModel)]="<PROPERTY_NAME>" // two-way data and event binding, for piping it has to be split into [ngModel]="... | <PIPE>" and (ngModel) <a routerLink="/todos">here</a> // router link [[Angular#Build-In_Directives|Directives]] Two-way binding notation '[()]' is also called banana-in-the-box. =====Template Variables===== '''Template Variables''' are defined by the prefix <code>#<NAME></code>. They can be referenced e.g. in the template in Typescript code e.g. ... <button type="button" (click)="callPhone(<NAME>.value)">Call</button> ... * [https://angular.io/guide/template-reference-variables documentation] =====Template Input Variables===== The '''let''' keyword declares a template input variable that you can reference within the template e.g. // see bookmarks.component.html <ng-template matMenuContent let-subMenuIndex="subMenuIndex"> <button mat-menu-item (click)="onViewMenu(subMenuIndex)">View Menu</button> =====ng-template===== With <code><ng-template></code> you can define template content that is only being rendered by Angular when you, whether directly or indirectly. =====Standard Events===== * click * dblclick * focus * blur * submit * scroll * cut * copy * paste * keydown * keypress * keyup * mouseenter * mousedown * mouseup * drag * dragover * drop =====Custom Events===== * sending custom events from child to parent @Component ... export class ... { @Output() public <EVENT_NAME> = new EventEmitter['''<'''<EVENT_TYPE>'''>'''](); // from @angular/core ... <METHOD>() { this.<EVENT_NAME>.emit([<VARIABLE_OF_EVENT_TYPE>]); * catching event in parent in parent HTML file: '''<'''<COMPONENT_SELECTOR> (<EVENT_NAME>)="<CODE>"'''>''' '''</'''<COMPONENT_SELECTOR>'''>''' =====Structural Directives===== '''Structural directives''' are directives which change the DOM layout by adding and removing DOM elements. They are generally are prefixed by an asterisk, <code>*</code>. =====Build-In Directives===== * [ngClass] // to set a style via a class * [ngStyle] // to set inline styles * [(ngModel)] // to bind properties * [ngIf] *ngIf='<PROPERTY_NAME>' // shows tag only if property is true * [ngFor] '''*ngFor="let''' todo '''of''' todos" * [ngSwitch] * <ng-container> ====Communication and Passing Data between Components==== * see http://dev-reboot.com/share-data/ =====Parent to Child Communication===== * create an input class property in the child component or use the input array of the @Component decorator e.g. @Input() myProperty: number @Component({ selector: 'child-component', inputs: ['count'], ... * and in the parent component template e.g. <child-component [myProperty]=value></child-component> * if needed react on changes (see [https://www.tektutorialshub.com/angular/angular-passing-data-child-component/ here]) =====Child to Parent Communication=====, * see [https://www.tektutorialshub.com/angular/angular-component-communication-sharing-data/ here] (e.g. by Events, Output decorator, ViewChild(), ...) ===Services=== Services provide specific functionality not directly related to views. Service providers can be injected into components as dependencies, making your code modular, reusable, and efficient. Modules, components and services are classes that use '''[[TypeScript#Decorators|decorators]]'''. These decorators mark their type and provide metadata that tells Angular how to use them. Services only live inside the scope of their providers, so in the scope of a module or a single component. They are instantiated when injected for the first time and keept alive as long as the provider exists. As services are normal classes, angulars lifecycle hooks do not apply to them. ===Angular Decorators=== ====ViewChild==== ViewChild is a property decorator that configures a view query. View queries are set before the ngAfterViewInit callback is called. ===Observables=== The observable (see [[JavaScript/JScript#RxJs|RxJS]]) pattern heavily used in Angular (see also [https://angular.io/guide/observables Angular documentation]). // create an observable timer$ = new Observable<string>( // new observable observer => { // '''subscriber function''' is executed when a consumer calls subscribe() and desribes how to generate values setInterval( () => observer.next(new Date().toString()), 10000); console.log("someone subscribed"); } ); var subscription: Subscription = timer$.subscribe({ // passing an '''observer''' which is an objects that defines the handler for the values it receives next(datestring) { // implements the Observer interface with callback methods for the 3 types of notifications console.log(datestring); // next (required), error and complete (optional) }, complete() { console.log("timer1_1 completed"); } }); ===Dependency Injection=== @Injectable({ providedIn: 'root' }) constructur(private <PROPERTY_NAME>: <TYP>) // depency injection ===Routing=== * see [https://indepth.dev/tutorials/angular/indepth-guide-to-passing-parameters-via-routing for a detailed description] or * [https://angular.io/guide/router-tutorial-toh#route-parameters Angular Router Tutorial] In Angular, the best practice is to load and configure the router in a separate, top-level module that is dedicated to routing and imported by the root AppModule. By convention, the module class name is <code>AppRoutingModule</code> and it belongs in the <code>app-routing.module.ts</code> in the <code>src/app</code> folder, which contains a routing table (sequence is important!!!): const routes: Routes = [ { path: '', component: LoginComponent}, // app root { path: 'bookmarks/menus/:id', component: MenuComponent}, { path: 'welcome/:name', component: WelcomeComponent}, // parameter { path: '**', component: ErrorComponent} // matches everything ]; and in template: <router-outlet></router-outlet> and in code: // see bookmarks.component.ts this.router.navigate( ['/menus', this.currentSubMenuObjects[subMenuIndex].uuid], // setting required route parameter { queryParams: { mode: "view"} } // setting query parameter ); ====Route Information==== To get information of the route in the target component include in the ctor: private route: ActivatedRoute, and // by snapshot this.uuid = this.route.snapshot.paramMap.get('uuid'); this.mode = this.route.snapshot.queryParamMap.get('mode'); // by observer this.id = +this.route.snapshot.params['id']; // to get parts of the this.route.queryParams.subscribe(params => {this.parentId = +params['parentId'];}); // to get query params ===PWA=== Progressive Web Apps (PWA) rely on '''Service Workers'''. Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs. When an application is loaded it is provided from the cache. In the background the service worker checks for an update and loads it to the cache. The new one is used next time the application is loaded. The version information is generated during build in <code>ngsw.json</code>. ====Implementation==== * [https://blog.angular-university.io/angular-service-worker/ Angular University detailed step by step guide] or * [https://morioh.com/p/984afc91af1c The complete Guide to Service Workers] * Progressive Web App (PWA) ng add @angular/pwa * creates e.g. <code>ngsw-config.json</code> which format is described [https://angular-doc.ru/guide/service-worker-config here] =====Debug Information===== * [https://angular.io/guide/service-worker-devops#locating-and-analyzing-debugging-information description] * see http://<URL>:<PORT>/ngsw/state e.g. http://127.0.0.1:8082/ngsw/state output [=== Version <HASH> Clients ... // clients with this version, could also be different tabs] =====Version Management===== [https://stackoverflow.com/questions/61042675/angular-pwa-update-is-too-slow Here] is a solution if the version update should be done immediately when the application is loaded. ===Angular Framework Modules=== * BrowserModule * Core ** @Component * [[Angular#FormsModule|Template Driven Forms (FormsModule)]] * [[Angular#HTTPModule|HTTPModule]] * [[Angular#Reactive_Forms|Reactive Forms (ReactiveFormsModule)]] * NgModule * see https://angular-training-guide.rangle.io/forms =====Template Driven Forms===== import {FormsModule} from "@angular/forms"; =====Reactive Forms===== * see [https://angular.io/guide/reactive-forms official documentation] * example see <code>menu.component.ts</code> and <code>menu.component.html</code> or <code>configuration.component</code> import {ReactiveFormsModule} from "@angular/forms"; ** <code>[formGroup]</code> directive ** <code>FormBuilder.group()</code> ** <code>setValue() or patchValue()</code> ** subscribe if needed ====HTTPModule==== * usage import { HttpClientModule } from '@angular/common/http'; import { HttpClient } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; * there are multiple overloads of <code>get()</code> * observables in general can emit multiple values but an observable returned by the get() method only emits once * All [[JavaScript/JScript#RxJs|observables]] returned from HttpClient methods are cold by design. Calling <code>subscribe()</code> triggers execution of the observable and causes HttpClient to compose and send the HTTP request to the server. * '''Completion''' or '''Error''' are mutually exclusive. * resources ** https://www.techiediaries.com/angular-11-tutorial-example-rest-crud-http-get-httpclient/ ===Angular CLI=== Angular '''C'''ommand '''L'''ine '''I'''nterface ng ng help ng version ====Add==== ng add ====Build==== ng build [--configuration production] // if production configuration build takes environment.prod.ts configuration, else environment.ts; --prod deprecated creates <code>dist</code> folder, which can be copied directly to a web server. The difference between prod and dev build is described [https://medium.com/@kavisha.talsania/angular-development-vs-production-build-671b7fd5dbf4 here]. ====E2E==== ng e2e runs and test the entire application, uses protractor. All tests are defined in folder <code>e2e</code>. ====Generate==== =====Component===== <APP_ROOT_DIR>'''>''' ng g[enerate] c[omponent] <COMPONENT_NAME> // leaf the Component part of the name, it will be added automatically, e.g. ng g c app-header // e.g. <ROOT_DIR>'''>'''ng g c features/bookmarks generates /src/app/<COMPONENT_NAME>/* and modifies <code>app.module.ts</code>. If COMPONENT_NAME starts with a small letter, the generated Typescript class and the NgModule declaration starts with a capital letter. <APP_ROOT_DIR>/src/app/<COMPONENT_DIR>'''>'''ng g c <COMPONENT_NAME> // generates new component in /src/app/<COMPONENT_DIR>/<COMPONENT_NAME>/* <APP_ROOT_DIR>/src/app'''>'''ng g c <COMPONENT_NAME> // generates new component in /src/app/<COMPONENT_NAME>/* =====Module===== ng g m <MODULE_NAME> // generates /src/app/<MODULE_NAME>/<MODULE_NAME>.modules.ts =====Service===== ng generate service <PATH>/<SERVICE_NAME> generates /src/app/<PATH>/<SERVICE_NAME>.service.ts ====Lint==== ng lint all rules are in <code>tslint.json</code>. ====New==== ng new <APP_NAME> creates: \<APP_NAME>\src\index.html // which contains the <app-root> tag \<APP_NAME>\src\app.component.ts // defines the root component class including <app-root> tag \<APP_NAME>\src\app.component.html // defines the root component template \<APP_NAME>\src\app-routing.modules.ts // contains all routings \<APP_NAME>\src\styles.css \<APP_NAME>\src\main.ts // bootstraps the [[#RootModule|root module]] which itself bootstraps the root component due to the bootstrap element of the @NgModule [[TypeScript#Decorators|decorator]] platformBrowserDynamic().bootstrapModule(AppModule) \<APP_NAME>\src\app\app.module.ts // defines the root module ====Test==== ng test uses Jasmine and Karma? and performs unit tests, see <code>app.component.spec.ts</code> ====Serve==== ng serve [--open // opens a browser with http://localhost:4200] [--port <PORT>] polls for code changes, builds it and loads it in the browser. ===Files and Directories=== /angular.json This file contains the settings of the Angular project (see [https://medium.com/nerd-for-tech/what-is-inside-of-angular-json-file-636e81e67651 here]). /tsconfig.json describes the translation from Typescript to Javascript. /README.md contains documentation. /package.json contains all dependencies, frameworks and tools. /src/polyfill.ts manages all browser incompabilities for Javascript. /src/styles.css contains all css styles for apps. /src/app/ contains all modules and components. /src/assets/ contains images /src/environments/ contains configurations for all environments like test, integration, qa, ... /src/node_modules all packages and frameworks installed due to listing in <code>package.json</code>. ===Style Guide=== * https://angular.io/guide/styleguide ==Installation== [[NodeJS#npm|npm]] install -g @angular/cli // -g installs [[Angular#Angular_CLI|Angular CLI]] it globally, not project-specific ng // Angular cli ng version // prints version cd C:\Uwes\typescripts\ mkdir angular // for examples and tests ===Update=== ng update // gives a list which can be updated manually by ng update @angular/<COMPONENT>, but everything has to be committed before ===Frontend Frameworks=== * [[Angular_Material|Angular Material]] seems to be the best choice * [https://www.jqwidgets.com/angular/ jqWidgets] ==Examples== ===Test1=== cd C:\Uwes\typescripts\angular ng [[Angular#New|new]] test1 // enforces strict type checking yes, router yes, CSS, cd test1 ng [[Angular#Serve|serve]] http://localhost:4200/ CTRL + C ... ng create services/data/messageData ===uweheuer Frontend (obsolete)=== * new version see [[Uweheuerfrontend|New UweHeuer Frontend]] cd C:\Uwes\typescripts\angular ng [[Angular#New|new]] uh-fe // strict type checking, router, CSS cd uh-fe ng add @angular/material // adds [[Angular_Material|Angular Material]], Indigo, no typography, browser animation // test by editing app.component.html [[Angular#Module|ng g m]] material // generates module // add import to app.module.ts [[Angular#Component|ng g c]] features/bookmarks [[Angular#Component|ng g c]] features/authentication ng g c features/home ng g c features/externals ng g c layout/header ng g c layout/footer ng g c layout/sidenav C:\Uwes\typescripts\angular\uh-fe\src\app\features\bookmarks> ng g c menu C:\Uwes\typescripts\angular\uh-fe> ng generate service services/backend/menuData C:\Uwes\typescripts\angular\uh-fe> ng generate service services/backend/bookmarksData C:\Uwes\typescripts\angular\uh-fe> ng generate service services/uiState C:\Uwes\typescripts\angular\uh-fe> npm i angular2-uuid -s ===Test Layout1=== cd cd C:\Uwes\typescripts\angular ng new layout-test1 // strict type checking, router, CSS cd layout-test1 npm i -s @angular/flex-layout @angular/cdk // from https://github.com/angular/flex-layout // add FlexLayoutModule to app.modules.ts ====ToDos==== * API Testtools e.g. Postman ** https://rapidapi.com/blog/best-api-testing-tools/ * single menu REST API ** https://stackoverflow.com/questions/44007188/deserialize-json-with-spring-unresolved-forward-references-jackson-exception ** https://stackoverflow.com/questions/17393812/json-and-java-circular-reference ** https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion ** https://github.com/jsog/jsog-jackson ** https://www.baeldung.com/spring-data-rest-relationships ** https://stackoverflow.com/questions/23767233/spring-data-rest-post-new-entity-with-relationships ** https://reflectoring.io/relations-with-spring-data-rest/ ** https://softwarehut.com/blog/tech/spring-data-rest-quick-easy-rest-jpa * UUID ** https://www.cloudhadoop.com/2018/10/angular-uuid-generate-unique-identifier.html ** https://stackblitz.com/edit/angular-uuid-generation * Menu and Url associative array ** https://visualstudiomagazine.com/articles/2016/01/01/exploiting-typescript-arrays.aspx ** Map<number, Menu> * Component State ** https://indepth.dev/posts/1408/how-to-manage-angular-state-in-your-components ** https://dev.to/avatsaev/simple-state-management-in-angular-with-only-services-and-rxjs-41p8 * https://offering.solutions/blog/articles/2018/11/21/online-and-offline-sync-with-angular-and-indexeddb/ * Progressive Web App (PWA) (IndexedDB) **[https://entwickler.de/online/javascript/progressive-web-apps-tipps-angular-579942201.html Angular and PWA] ** https://www.thinktecture.com/de/angular/anwendung-offline-nehmen/ ** https://entwickler.de/online/development/offlinemodus-progressive-web-apps-579874341.html ** https://dimitr.im/progressive-web-apps-angular-cli * Toolboar for total app navigation * Toogle Group with Icons for Bookmarks View * Sidenav for full app ** https://stackblitz.com/edit/angular-material-toggle-sidenav-in-another-component?file=src%2Fapp%2Flayouts%2Fdrawer%2Fdrawer.component.ts ** https://stackoverflow.com/questions/48073057/open-close-sidenav-from-another-component ** https://stackblitz.com/angular/lyabryrmmpk?file=src%2Fapp%2Fsidenav-backdrop-example.html ** https://stackoverflow.com/questions/56357598/how-to-toggle-mat-sidenav-in-another-component?rq=1 ** https://stackoverflow.com/questions/40820354/setting-sidenav-below-toolbar-in-angular-material-design?rq=1 ** https://stackblitz.com/edit/angular-v6xwte?file=src%2Fapp%2Fapp.component.html * Angular Forms Module * Flex Layout ** http://dev-reboot.com/pwa-navigation/ ** https://www.barbarianmeetscoding.com/blog/building-beautiful-web-apps-with-angular-material-part-ii ** https://www.youtube.com/watch?v=QNykkMog0rc * adding components dynamically ** https://javascript.plainenglish.io/dynamic-tab-based-application-using-angular-material-9f9da7de5732 * add Host Listener ** https://angular.io/guide/inputs-outputs ** https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-2-hostlistener-1b66d45b3e3d ** https://medium.com/@mirokoczka/3-ways-to-communicate-between-angular-components-a1e3f3304ecb * Menu ** http://embed.plnkr.co/0I8C8RbhvyoEjEoLZksz/ Menu Trigger Data * Bookmark Tree View ** https://medium.com/@vag/angular-material-tree-26adccadc63b ** https://stackblitz.com/edit/angular-ax72ew?file=app%2Ftree-checklist-example.ts ** https://stackblitz.com/edit/angular-material-nested-tree-with-updates?file=src%2Fapp%2Ftree-datasource.ts *** https://github.com/angular/components/issues/11381 *** https://medium.com/@vag/angular-material-tree-26adccadc63b *** https://docs.google.com/presentation/d/1BoJ-jq-O9zQHAps7LVciiiH9WI9dDqqv-LAlQ6iMh5o/htmlpresent *** https://angular2-tree.readme.io/docs/changing-the-tree ** https://www.youtube.com/watch?v=s0Vy3sLbeyA *** https://stackblitz.com/edit/material-tree-flat *** https://stackblitz.com/edit/material-tree-nested nested tree with lines *** https://stackblitz.com/edit/material-tree-checklist *** https://stackblitz.com/edit/material-tree flat tree with icon (best fit) *** https://stackblitz.com/edit/material-tree-dynamic with loading animmation ** https://stackblitz.com/edit/angular-material-tree-example ** https://www.youtube.com/watch?v=BALaj39rbZE flat tree with check boxes ** https://stackblitz.com/edit/ng-mat-tree-test-7 nested tree with icons ** https://blog.briebug.com/blog/angular-how-to-implement-drag-and-drop-in-a-material-tree Drag and Drop ==Resources== * [https://angular.io/guide/setup-local Official Getting Started] * [https://angular.io/docs Official Documentation] * C:\Uwes\owncloud\documents\Software_Development\Programming\Frameworks\Angular\Angular.drawio * [https://angular-university.io/lesson/angular-beginners-course-kickoff Angular University Beginners Course] * [https://www.angularjswiki.com/ Angular Wiki]
Summary:
Please note that all contributions to Wiki RB4 may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Uwe Heuer Wiki New:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Toggle limited content width