41,99 €
Unleash the power of PrimeNG components to design compelling user interface for your Angular applications
This book is for everybody who would like to learn or create modern Angular based single page applications using PrimeNG component library. This book is a good choice for beginners to advanced users who are serious to learn modern Angular applications. The prerequisites for this book are some basic knowledge on the Angular 2+ version with TypeScript and CSS skills.
PrimeNG is a leading UI component library for Angular applications with 80+ rich UI components. PrimeNG was a huge success in the Angular world and very quickly. It is a rapidly evolving library that is aligned with the last Angular release. In comparison with competitors, PrimeNG was created with enterprise applications in mind. This book provides a head-start to help readers develop real–world, single-page applications using the popular development stack.
This book consists of 10 chapters and starts with a short introduction to single-page applications. TypeScript and Angular fundamentals are important first steps for subsequent PrimeNG topics. Later we discuss how to set up and configure a PrimeNG application in different ways as a kick-start. Once the environment is ready then it is time to learn PrimeNG development, starting from theming concepts and responsive layouts. Readers will learn enhanced input, select, button components followed by the various panels, data iteration, overlays, messages and menu components. The validation of form elements will be covered too. An extra chapter demonstrates how to create map and chart components for real-world applications. Apart from built-in UI components and their features, the readers will learn how to customize components to meet their requirements.
Miscellaneous use cases are discussed in a separate chapter, including: file uploading, drag and drop, blocking page pieces during AJAX calls, CRUD sample implementations, and more. This chapter goes beyond common topics, implements a custom component, and discusses a popular state management with @ngrx/store. The final chapter describes unit and end-to-end testing. To make sure Angular and PrimeNG development are flawless, we explain full-fledged testing frameworks with systematic examples. Tips for speeding up unit testing and debugging Angular applications end this book.
The book is also focused on how to avoid some common pitfalls, and shows best practices with tips and tricks for efficient Angular and PrimeNG development. At the end of this book, the readers will know the ins and outs of how to use PrimeNG in Angular applications and will be ready to create real- world Angular applications using rich PrimeNG components.
Step-by-step practical approach
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 360
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2017
Production reference: 1250717
ISBN 978-1-78829-957-2
www.packtpub.com
Authors
Sudheer Jonna
Oleg Varaksin
Copy Editor
Charlotte Carneiro
Reviewer
Aristides Villarreal Bravo
Project Coordinator
Sheejal Shah
Commissioning Editor
Smeet Thakkar
Proofreader
Safis Editing
Acquisition Editor
Reshma Raman
Indexer
Rekha Nair
Content Development Editor
Jason Pereira
Production Coordinator
Melwyn D'sa
Technical Editor
Prajakta Mhatre
Angular is a sophisticated technology that aims to create a framework with multi-platform support, including web, mobile and desktop. When I heard the news about Angular 1 being rewritten for Angular 2, I got excited instantly, since it was an opportunity for us to develop a UI component suite that I was pretty sure would be a success similar to its predecessor.
Then at the beginning of 2016, with the early alpha releases of Angular, we started working on PrimeNG to bring our years of expertise in PrimeFaces, the most popular UI framework for JavaServer Faces to Angular. Initially, we hit some roadblocks in the technology that prevented us from developing what we had in mind; however, all of those were temporary and the more we worked with Angular, the more we started to realize its true potential. From the perspective of a UI component library, Angular gives us all the APIs we need to develop easy to use, customizable, and accessible components easily.
Currently, PrimeNG is the most complete UI solution for Angular web development, with over 70+ high quality components and over a hundred thousand download per month. PrimeNG aims to solve complex enterprise requirements and as a result, its feature set is way beyond other UI libraries. As with all other PrimeTek libraries, PrimeNG is open source under the MIT license, which enables us to combine the power of the open source community with professional services and add-ons.
The standard documentation along with the showcase are the core resources for PrimeNG; however, there are many cases that cannot be covered in the documentation, and Angular UI Development with PrimeNG fills this gap and offers practical examples to serve as a companion to enhance your PrimeNG experience. I have known the authors, Oleg and Sudheer, for a long time and they have years of expertise in Prime projects, such as PrimeFaces before, and now PrimeNG. Their extensive knowledge of PrimeNG that is documented in this book is the best complementary PrimeNG resource available.
Overall, Angular and PrimeNG are a great duo for any type of Angular web application and considering the fact that both are developed with high pace, we can expect greater benefits in the future.
Cagatay Civici
Founder and Creator of PrimeNG
Sudheer Jonna was born in Nellore, India. Currently, he works as a senior software engineer in Singapore. He completed his master's degree in computer applications from JNTU University. In the past few years, he has worked on building various Java and JavaScript web applications based on JSF, PrimeFaces, Struts, Spring, REST, jQuery, Angular, React, and VueJS. He has also worked on many JavaEE and API development technologies, such as JPA (Hibernate), EJB, GraphQL, and Sequelize. He is the founder of GeekoTek company (http://geekotek.com) and is a longtime JSF and Prime products expert. He is also a project member of the PrimeFaces, PrimeFaces Extensions, and PrimeNG open source projects. He is the author of three other Packt books, titled Learning PrimeFaces Extension Development, PrimeFaces BluePrints, and PrimeFaces Theme Development. He has worked as a technical reviewer on a few books. He is a regular speaker, trainer, reviewer, blogger, organizer, and active member of public forums. He is interested in R&D on the latest technologies. He shares his knowledge through his personal website, http://sudheerjonna.com. You can follow him on Twitter with the handle @SudheerJonna.
Oleg Varaksin is a senior software engineer living in the Black Forest, Germany. He is a graduate computer scientist who studied informatics at Russian and German universities. His main occupation and "daily bread" in the last few years has consisted of building various Java-and JavaScript-based web applications based on JSF, PrimeFaces, Spring, REST, JavaScript, jQuery, Angular, and HTML5. Currently, he is working at Swiss Federal Railways on a new ticket webshop.
Oleg is an experienced and passionate web developer and has been working with the Prime UI libraries from the beginning. He is also a well-known member of the PrimeFaces community, creator of the PrimeFaces Extensions project, and the author of the PrimeFaces Cookbook. Oleg loves JavaScript, new ECMAScript standards, TypeScript, Angular, PrimeNG, RxJS, and Redux architecture. He has a deep understanding of web usability and accessibility.
Oleg normally shares the knowledge he has acquired on his blog at https://medium.com/@OlegVaraksin. His Twitter handle is @OlegVaraksin.
Aristides Villarreal Bravo is a Java developer. He is a member of the NetBeans Dream Team and Java User Groups. He is also the developer of the jmoordb framework. He lives in Panama.
He has organized and participated in various conferences and seminars related to Java,JavaEE, NetBeans, the NetBeans platform, free software, and mobile devices nationally andinternationally.
He is a writer of tutorials and blogs about Java NetBeans, and web developers.He has participated in several interviews on sites such as NetBeans, NetBeans Dzone, andJavaHispano. He has also developed plugins for NetBeans.
He is the CEO of Javscaz Software Developers and has reviewed a number of books, such as PrimeFaces Blueprints, Apache Hive Cookbook, Dart By Example, and Express.js Blueprints, all by Packt.
For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Getting Started with Angular and PrimeNG
TypeScript fundamentals
Basic types
Interfaces, classes, and enums
Functions
Generics
Modules
Advanced types, decorators, and compiler options
Union types and type aliases
Type inference
Decorators
Type definition files
Compiler options
Angular cheat sheet - overview of key concepts
Components, services, and dependency injection
Templates and bindings
Built-in directives
Communication between components
Forms
Routing
Angular modularity and lifecycle hooks
Modules and bootstrapping
Lifecycle hooks
Running PrimeNG with SystemJS
The SystemJS configuration for Angular
Adding PrimeNG dependencies
Setting up PrimeNG project with Webpack
Entry point and output
Loaders and plugins
Adding PrimeNG, CSS, and SASS
Setting up PrimeNG project with Angular CLI
Generating scaffolding
Adding PrimeNG dependencies
Summary
Theming Concepts and Layouts
Understanding structural and skinning CSS
Organizing your project structure with Sass
Simple ways to create a new theme
ThemeRoller approach
The Sass approach
The responsive grid system in PrimeNG
Basic principles
Nested columns
Responsive and fluid layout
Bootstrap flexbox layout meets PrimeNG
Summary
Enhanced Inputs and Selects
Formatted input with InputMask
Mask format options
Using the slot character
Making a part of the mask optional
Autosuggestion with AutoComplete
Multiple selection
Working with objects
Advanced features - the customized content displays
Entering multiple values with Chips
Display complex information using template
Discovering checkbox - boolean, many, and TriState
Boolean checkbox - single selection
Checkbox multiple selection
Multistate representation - TriStateCheckbox
Choosing items with single and MultiSelect components
Customized Dropdown
The MultiSelect dropdown
Basic and advanced Calendar scenarios
Localization
Time picker options
Advanced features
Spinner and Slider – different ways to provide input
Advanced features - going beyond basic usage
Slider
Advanced features - going beyond basic usage
Text editing with rich editors
The customized editor
Password and star-based rating inputs
Rating input
Validation with the input and select components
Summary
Button and Panel Components
Enhanced Button, RadioButton, and SplitButton
Button
Icons and severity
RadioButton
SplitButton
Icons and theming
Selecting a value with ToggleButton and SelectButton
SelectButton
Grouping buttons with Toolbar
Arranging your view with Panels and FieldSets
Panel
FieldSet
Vertical stacked panels with Accordion
Grouping content with tabs in TabView
Summary
Data Iteration Components
Multi feature DataTable
Change detection
Dynamic columns
Selecting rows in DataTable
Single selection
Multiple selection
RadioButton selection
Checkbox selection
Sorting, filtering, and paginating data in DataTable
Sorting
Filtering
Pagination
Customizing the cell content with templating
Resizing, reordering, and toggling columns in DataTable
Resizing
Reordering
Toggling
In-cell editing with DataTable
Making DataTable responsive
Using column and row grouping
Column grouping
Row grouping
Expandable row groups
Sub-headers
RowSpan groups
Handling tons of data with lazy DataTable
Row expansion by providing a row template
Exporting data in CSV format
DataTable events and methods
Listing data with DataList
Facets and pagination
Lazy loading
Events
Listing data with PickList
Listing data with OrderList
Grid-organized data with DataGrid
Beyond basic usage - advanced features
On-demand data loading with DataScroller
Lazy loading
Visualizing data with Tree
Selection features - single, multiple, and checkbox
Beyond basic usage - advanced features
Visualizing data with TreeTable
Selection features - single, multiple, and checkbox
Beyond basic usage - advanced features
Managing events with Schedule
Header customization
Beyond basic usage - advanced features
Events and methods
Summary
Amazing Overlays and Messages
Displaying content in the popup mode
Dialog
Usability features
Customized header and footer
ConfirmDialog
Customization
Multipurpose scenarios with OverlayPanel
Integration with other components
Closable properties
Displaying content in Lightbox
Custom content mode
Transition effects
Notifying users with Messages and Growl
Growl - another way of notifying information
Sticky behavior
Tooltips for form components
Summary
Endless Menu Variations
Creating programmatic menus using the MenuModel API
Menu actions
Statically and dynamically positioned menus
Accessing commands via MenuBar
ContextMenu with nested items
Customized target for ContextMenu
DataTable integration
SlideMenu – menu in the iPod style
TieredMenu – sub-menus in nested overlays
MegaMenu – the multicolumn menu
PanelMenu – hybrid of Accordion and Tree
TabMenu - menu items as tabs
Breadcrumb – providing contextual information about the page hierarchy
Summary
Creating Charts and Maps
Working with the chart model
Chart types
Customization
Events
Data representation with line and bar charts
Data representation with pie and doughnut charts
Data representation with radar and polar area charts
Drawing an organization chart for the relationship hierarchy
Hierarchical data with zero configuration
Advanced customization
Selection and events
Basic integration with the Google Maps API
Various use cases with the GMap component
Overlays
Events
Summary
Miscellaneous Use Cases and Best Practices
File uploading in all its glory
Basic, multiple, and automatic file uploading
Restrictions by file types and size
Customizations
Learning draggable and droppable directives
Draggable
Droppable
Displaying a collection of images with Galleria
Get it up and running
Auto play mode and effects
Events
CRUD sample implementation with DataTable
Deferring mechanism to optimize page loading
Blocking page pieces during long-running AJAX calls
Process status indicator in action
Selecting colors with ColorPicker
Displaying confirmation dialog with guarded routes
Implementing a custom wizard component with Steps
Introduction to state management with @ngrx/store
Redux principles
CRUD application with @ngrx/store
Summary
Creating Robust Applications
Setting up unit testing with Jasmine and Karma
Brief introduction to Jasmine
Testing setup with Webpack and Karma
Unit testing of components and services
Angular testing utilities
Testing a component
Testing a service
Tips on how to speed up unit testing
Setting up the e2e test environment with Protractor
Installing and configuring Protractor
Writing automated UI tests at a glance
Browser object, element, and locators
Clean architecture with Page Objects
Writing complete the e2e test
Exploring a PrimeNG application with Augury and ng.probe
Augury in action
Debugging with ng.probe
Summary
PrimeNG is a leading UI component library for Angular single page applications with 80+ rich UI components. PrimeNG has had huge success in the Angular world due to its active development over a short space of time. It is a rapidly evolving library, which is aligned with the last Angular release. Unlike this competitors, PrimeNG was created with enterprise applications in mind. This book provides a headstart for readers who want to develop real-time single page applications using this popular development stack. This book consists of ten chapters and starts with a short introduction to single page applications. TypeScript and Angular fundamentals are important first steps for the PrimeNG topics that follow. Later, it discusses how to set up and configure a PrimeNG application in different ways for a kick-start. Once the environment is ready, then it is time to learn PrimeNG development, starting with the concept of theming and responsive layouts. Readers will learn enhanced Input, Select, and Button components, followed by various Panel, DataIteration, Overlays, Messages, and Menu components. The validation of form elements will not be missed out. An extra chapter demonstrates how to create map and chart components for real-world applications. Apart from the built-in UI components and their features, readers will see how to customize components as per their requirements. Miscellaneous use cases are discussed in a separate chapter. Just to name a few: file uploading, drag and drop, blocking page pieces during AJAX calls, CRUD sample implementation, and more. This chapter goes beyond common topics, implements a custom component, and discusses a popular form of state management with @ngrx/store. The final chapter describes unit and end-to-end testing. To make sure Angular and PrimeNG development is flawless, full-fledged testing frameworks will be explained with systematic examples. Tips for speeding up unit testing and debugging Angular applications round out this book. The book also focuses on how to avoid some common pitfalls, and shows best practices with tips and tricks for efficient Angular and PrimeNG development. At the end of this book, readers will know the ins and outs of how to use PrimeNG in Angular applications and get ready to create real-world Angular applications using rich PrimeNG components.
Chapter 1, Getting Started with Angular and PrimeNG, gives you the knowledge you need to dive into the next chapters. The chapter gives an overview of the TypeScript and Angular constructs used in this book. It is not possible to explain numerous features in detail. Instead, we will concentrate on the most important key concepts such as types, template syntax, decorators, component communication scenarios, modularity, and lifecycle hooks. After that, this chapter will introduce PrimeNG, which consists of rich UI components for Angular 2+, and show three possible project setups using SystemJS and Webpack loaders, as well as Angular CLI, a command-line tool for blazing fast Angular development.Chapter 2, Theming Concepts and Layouts, introduces PrimeNG themes and the concepts involved. Readers will learn about the theming of PrimeNG components. The difference between structural and skinning CSS, the recommended project structure when working with SASS, installing and customizing PrimeNG themes and creating new themes will all be detailed. A discussions of two variants of responsive layouts, PrimeNG's own grid system, and Bootstrap's flexbox grid, finish this chapter.Chapter 3, Enhanced Inputs and Selects, explains how to work with the input and select components available in PrimeNG. Such components are the main parts of every web application. PrimeNG provides nearly 20 components for data input that extend the native HTML elements with user-friendly interfaces, skinning capabilities, validation, and many other useful features.Chapter 4, Button and Panel Components, covers various buttons such as radio, split, toggle, and select buttons, and Panel components, such as Toolbar, Accordion, FieldSet, and tabbed view. Panel components act as container components, which allow the grouping of other components. Various settings to configure Panel components are detailed in this chapter.Chapter 5, Data Iteration Components, covers basic and advanced features to visualize data with the data iteration components provided by PrimeNG, including DataTable, DataList, PickList, OrderList, Tree, and TreeTable. The features discussed include sorting, pagination, filtering, lazy loading, and single and multiple selections. Advanced data visualization with the Schedule and DataScroller components will be demonstrated as well.Chapter 6, Amazing Overlays and Messages, demonstrates a range of variations in content, displaying in modal or non-modal overlays such as Dialog, LightBox, and Overlay panel. The user does not leave the page flow when the content is displayed in the mentioned Overlays. An Overlay component overlays other components on a page. PrimeNG also offers notification components to show any messages or advisory information. Those components will be described as well.
Chapter 7, Endless Menu Variations, explains several menu variations. PrimeNG's menus fulfill all major requirements. They come with various facets--static, dynamic, tiered, hybrid, iPod-styled, and so on, and leave nothing to be desired. Readers will see a lot of recipes that discuss menu structure, configuration options, customizations, and integration with other components.Chapter 8, Creating Charts and Maps, covers the ways to create visual charts with PrimeNG's extensive charting features and maps based on Google Maps. PrimeNG offers basic and advanced charting with its easy-to-use and user-friendly charting infrastructure. Besides standard charts, the chapter shows a special organization chart for visualizing hierarchical data. Throughout the chapter, mapping abilities such as drawing polylines, polygons, handling markers, and events will be explained as well.Chapter 9, Miscellaneous Use Cases and Best Practices, introduces more interesting features of the PrimeNG library. You will learn about file uploading, drag and drop capabilities, displaying collections of images, practical CRUD implementation, deferred page loading, blocking page pieces, displaying a confirmation dialog with guarded routes, and more. An extra section will go through the complete process of building reusable components and developing a custom wizard component. After reading this chapter, readers will be aware of state-of-the-art state management with @ngrx/store and will see the benefits of Redux architecture.Chapter 10, Creating Robust Applications, describes unit and end-to-end testing. The chapter begins with setting up a test environment with Jasmine and Karma. To make sure Angular and PrimeNG development is flawless, full-fledged testing frameworks will be explained with systematic examples. Tips for speeding up testing and debugging Angular applications end this chapter.
This book will guide you through the installation of all the tools that you need to follow the examples. You will need to install npm to effectively run the code samples present in this book.
This book is for everybody who would like to learn to create modern Angular-based single page applications using the PrimeNG component library. This book is a good choice for beginner to advanced users who are serious about learning modern Angular applications. The prerequisites for this book are some basic knowledge of Angular 2+, as well as TypeScript and CSS skills.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub:
https://github.com/ova2/angular-development-with-primeng
.
Every chapter has section-driven sub-folders with README files that contain all required instructions on how to run a demo applications. All demo applications in the book were developed with Angular 4 and PrimeNG 4.
https://github.com/PacktPublishing/Angular-UI-Development-with-PrimeNG
.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/LearningAngularUIDevelopmentwithPrimeNG_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
This book presupposes some basic knowledge of TypeScript and Angular 2. Anyway, we would like to give the readers an overview of the most important TypeScript and Angular key concepts used in this book. We will summarize TypeScript and Angular features and present them in understandable, simple, but deeply explained portions. At the time of writing the book, the current TypeScript and Angular Versions are 2.3.x and 4.2.x, respectively. Readers will also meet the PrimeNG UI library for the first time and gain experience with project setups in three various ways. At the end of this chapter, readers will be able to run the first Angular- and PrimeNG-based web application.
In this chapter, we will cover the following topics:
TypeScript fundamentals
Advanced types, decorators, and compiler options
Angular cheat sheet - overview of key concepts
Angular modularity and lifecycle hooks
Running PrimeNG with SystemJS
Setting up PrimeNG project with Webpack
Setting up PrimeNG project with Angular CLI
Angular 2 and higher is built with features of ECMAScript 2015/2016 and TypeScript. The new ECMAScript standards target evergreen browsers and helps to write more powerful, clean, and concise code. You can also use these features in any other less modern browsers with Polyfills such as core-js (https://github.com/zloirock/core-js). But, why do we need to use TypeScript?
TypeScript (http://www.typescriptlang.org) is a typed language and a super set of JavaScript developed by Microsoft. One can say that TypeScript is an advanced JavaScript with optional static typing. TypeScript code is not processed by browsers, it has to be translated into JavaScript by means of a TypeScript compiler. This translation is called compilation or transpilation. The TypeScript compiler transpiles .ts files into .js files. The main advantages of TypeScript are as follows:
Types help you find and fix a lot of errors during development time. That means, you have less errors at runtime.
Many modern
ECMAScript
features are supported out of the box. More features are expected according to the roadmap (
https://github.com/Microsoft/TypeScript/wiki/Roadmap
).
Great tooling and IDE support with IntelliSense makes the coding a pleasure.
It is easier to maintain and refactor a TypeScript application than one written in untyped JavaScript.
Developers feel comfortable with TypeScript due to object-oriented programming patterns, such as interfaces, classes, enums, generics, and so on.
Last but not least, Angular 2+ and PrimeNG are written in TypeScript.
It is also important to keep the following points in mind:
The Typescript Language Specification says,
every JavaScript program is also a TypeScript program
. Hence, a migration from JavaScript to TypeScript code is easily done.
TypeScript compiler emits output even when any errors are reported.
In the next section,
Advanced types, decorators, and compiler options
, we will see how we can forbid emitting JavaScript on errors.
What is the best way to learn the TypeScript language? There is an official handbook on the TypeScript's homepage, which is aligned with the last released version. Hands-on learning is possible with the TypeScript playground (http://www.typescriptlang.org/play), which compiles on-the-fly TypeScript code entered in a browser and shows it side by side with the generated JavaScript code:
Alternatively, you can install the TypeScript globally by typing the following command in the command line:
npm install -g typescript
Global installation means, the TypeScript compiler tsc can be reached and used in any of your projects.Installed Node.js and npm are presupposed. Node.js is the JavaScript runtime environment (https://nodejs.org). npm is the package manager. It is shipped with Node.js, but can be installed separately as well. After that, you can transpile one or more .ts files into .js files by typing the following command:
tsc some.ts another.ts
This will result in two files, some.js and another.js.
TypeScript has more types and advanced constructs such as decorators and type definition files. This chapter gives an overview on advanced topics and shows how to customize the compiler configuration.
A union type describes a value that can be one of many types. The vertical bar | is used as separator for each type the value can have. For instance, number | string
