Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
1.
Get the fullebook with Bonus Features for a Better Reading Experience on ebookgate.com Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri https://ebookgate.com/product/angular-up-and-running- learning-angular-step-by-step-1st-edition-shyam-seshadri/ OR CLICK HERE DOWLOAD NOW Download more ebook instantly today at https://ebookgate.com
2.
Instant digital products(PDF, ePub, MOBI) available Download now and explore formats that suit you... XML Step by Step Second Edition Step By Step Microsoft Michael J. Young https://ebookgate.com/product/xml-step-by-step-second-edition-step-by- step-microsoft-michael-j-young/ ebookgate.com Picture Yourself Learning Microsoft Excel 2010 Step by Step 1st Edition Deidre Hayes https://ebookgate.com/product/picture-yourself-learning-microsoft- excel-2010-step-by-step-1st-edition-deidre-hayes/ ebookgate.com Dressmaking Step by Step Alison Smith https://ebookgate.com/product/dressmaking-step-by-step-alison-smith/ ebookgate.com Picture Yourself Learning Microsoft Word 2010 Step by Step 1st Edition Diane (Diane Koers) Koers https://ebookgate.com/product/picture-yourself-learning-microsoft- word-2010-step-by-step-1st-edition-diane-diane-koers-koers/ ebookgate.com
3.
Dermatologic Surgery Stepby Step 1st Edition Keyvan Nouri https://ebookgate.com/product/dermatologic-surgery-step-by-step-1st- edition-keyvan-nouri/ ebookgate.com Step by Step LASIK Surgery 1st Edition Namrata Sharma https://ebookgate.com/product/step-by-step-lasik-surgery-1st-edition- namrata-sharma/ ebookgate.com Microsoft Silverlight 4 Step by Step Laurence Moroney https://ebookgate.com/product/microsoft-silverlight-4-step-by-step- laurence-moroney/ ebookgate.com Step by step Bread 1st American ed Edition Caroline Bretherton https://ebookgate.com/product/step-by-step-bread-1st-american-ed- edition-caroline-bretherton/ ebookgate.com PC Markanda Arbitration Step by Step Markanda P C https://ebookgate.com/product/pc-markanda-arbitration-step-by-step- markanda-p-c/ ebookgate.com
Introduction It’s funny thatwe constantly over- or underestimate the impact of certain events and projects in our lives. I seriously believed that the last project I worked on at Google, Google Feedback, would end up completely changing how the company interacted with its customers. And I believed Angular (AngularJS at the time) would just be another flash-in-the-pan, yet-another-framework that would not outlive the Feed‐ back project’s admin interface. And in hindsight, it was exactly the other way around. While Feedback still exists and is baked into a lot of Google products, it is Angular that has gone from a tiny project used by one internal team at Angular to now being used by thousands of developers and companies worldwide. And a lot of it stems from Misko, Igor, and the entire team around it, and their unerring dedication to improving how we develop web applica‐ tions. What started off as a two-member project is now one of the largest open source com‐ munities on the web, and the framework has impacted and been a part of thousands of projects across the world. There are dozens of books, hundreds of tutorials, and thousands of articles on Angular, and Angular’s adoption and support continues to grow each day. Some of the major concepts that were ahead of their time during the first version of Angular (like data binding, separation of concerns, dependency injection, etc.) are now common features of new frameworks. The biggest change to the AngularJS ecosystem has been the release of the new ver‐ sion of Angular (initially called Angular 2.0, now just called Angular). It was a drastic, non-backward-compatible change that almost divided an entire community. But with community engagement and an open, inclusive team, what could have been a disas‐ trous step turned out to be a much needed overhaul of Angular to bring it to the new age of web development. ix
16.
Truly, what makesAngular a great technology and framework is the community around it—those who contribute to the core framework, or develop plug-ins for it, as well as those who use it on a day-to-day basis. As part of the community, I am truly excited to present this book, and contribute in my own way to what makes this community great. Who Should Read This Book This book is for anyone who is looking to get started with Angular (2.0 and onward), whether as a side project, as an additional tool, or for their main work. It is expected that readers are comfortable with JavaScript and HTML before starting this book, but a basic knowledge of JavaScript should be sufficient to learn Angular. Knowledge of AngularJS 1.0 is not needed or expected. We will also use TypeScript, which is the recommended way of developing in Angu‐ lar, but a preliminary knowledge is sufficient to read this book. We will take it step by step, so relax and have fun learning with me. Why I Wrote This Book Angular as a framework has grown immensely, and comes with a large set of features and capabilities. With a large community behind it, it also comes with an influx of helpful content. But the help content, tutorials, and guides are either focused only on particular topics, or sporadic and not necessarily useful for someone getting started. The aim of this book is to provide a step-by-step guide on getting started with Angu‐ lar. Each concept is provided in a logical, organized fashion, building on top of the previous one. With so many moving parts and an active community, this book does not intend to cover each and every aspect, but instead focuses on the core building blocks in a detailed fashion while letting readers discover the rest on their own. At the end of the book, you should be familiar with a majority of the Angular frame‐ work, and be able to use Angular to develop your own web applications and use it in your own projects. A Word on Web Application Development Today JavaScript has come a long way, to the point where it is one of the most widely used and adopted programming languages. Nowadays, it’s rare for web developers to have to worry about browser inconsistencies and the like, which was the primary reason for frameworks like jQuery to have existed. x | Introduction
17.
Frameworks (like Angularand React) are now a very common choice for developing frontend experiences, and it is rare for anyone nowadays to decide to build a frontend application without leveraging one. The advantages of using frameworks are manifold, from reducing boilerplate code, to providing a consistent structure and layout for developing an application to many more. The primary intent is always to reduce the time spent on cruft, and focus more on the major functionality we want to provide. And if it works across browsers (and platforms, like Android and iOS, in addition to desktop), then more power to it. Angular (as well as other frameworks) provides this, primarily through some core fundamentals that are at the heart of the framework, including: • Powerful templating syntax driven by declarative programming • Modularity and separation of concerns • Data binding, and through it, data-driven programming • Testability and awesome testing support • Routing and navigation • And a host of other features, from server-side rendering, to the ability to write native mobile applications, and much more! With the help of Angular, we can focus on building amazing experiences, while man‐ aging complexity and maintainability in a seamless fashion. Navigating This Book This book aims to walk a developer through each part of Angular, step by step. Each chapter that introduces a new concept will be immediately followed by a chapter on how we can unit test it. The book is roughly organized as follows: • Chapter 1, Introducing Angular, is an introduction to Angular as well as the con‐ cepts behind it. It also covers what it takes to start writing an Angular application. • Chapter 2, Hello Angular, walks through creating a very simple Angular applica‐ tion, and diving into how the pieces work together. It also introduces the Angular CLI. • Chapter 3, Useful Built-In Angular Directives, digs into the basic built-in Angular directives (including ngFor, ngIf, etc.) and when and how to use them. • Chapter 4, Understanding and Using Angular Components, covers Angular com‐ ponents in more detail, as well as the various options available when creating them. It also covers the basic lifecycle hooks available with components. Introduction | xi
18.
• Chapter 5,Testing Angular Components, introduces how to unit test angular com‐ ponents using Karma and Jasmine, along with the Angular testing framework. • Chapter 6, Working with Template-Driven Forms, covers creating and working with forms in Angular, specifically template-driven forms. • Chapter 7, Working with Reactive Forms, covers the other way of defining and working with forms, which is how to create and develop reactive forms. • Chapter 8, Angular Services, covers Angular services, which includes how to use built-in Angular services, as well as how and when to define our own Angular services. • Chapter 9, Making HTTP Calls in Angular, moves into the server communication aspect of Angular, and delves into making HTTP calls, as well as some advanced topics like interceptors and the like. • Chapter 10, Unit Testing Services, takes a step back and covers unit testing again, but this time with a focus on unit testing services. This includes testing simple services and slightly harder cases like asynchronous flows as well as services and components that make HTTP calls. • Chapter 11, Routing in Angular, goes in depth into how we can accomplish rout‐ ing in an Angular application and covers the Angular routing module in detail as well as a majority of its features. • Chapter 12, Productionizing an Angular App, finally brings together all the con‐ cepts and covers taking the developed Angular application to production and the various concerns and techniques involved in the same. The entire code repository is hosted on GitHub, so if you don’t want to type in the code examples from this book, or want to ensure that you are looking at the latest and greatest code examples, visit the repository and grab the contents. This book uses AngularJS version 5.0.0 for all its code examples. Online Resources The following resources are a great starting point for any AngularJS developer, and should be always available at your fingertips: • The Official Angular API Documentation • The Official Angular Quickstart Guide • The Angular Heroes Tutorial App xii | Introduction
19.
Conventions Used inThis Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/shyamseshadri/angular-up-and-running. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples Introduction | xiii
20.
from O’Reilly booksdoes require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a signifi‐ cant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Angular: Up and Running by Shyam Seshadri (O’Reilly). Copyright 2018 Shyam Seshadri, 978-1-491-99983-7.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Safari Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals. Members have access to thousands of books, training videos, Learning Paths, interac‐ tive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐ sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others. For more information, please visit http://oreilly.com/safari. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/angularUR. To comment or ask technical questions about this book, send email to bookques‐ tions@oreilly.com. xiv | Introduction
21.
For more informationabout our books, courses, conferences, and news, see our web‐ site at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments This book is dedicated to my wife, Sanchita, and my parents and grandmom who were my rock as well as my motivation to write this book in the best manner I could, all the while balancing my own fledgling startup in its most precarious time (the beginning!). I’d also like to thank my reviewers, Yakov Fain and Victor Mejia, who had to read and review my unedited ramblings and make sure I got my point across in the most suc‐ cinct and understandable terms. This book of course wouldn’t be possible without the faith and efforts of the awesome team at O’Reilly, especially Angela and Kristen! And finally, thank you to the amazing Angular community for all their contributions, feedback, and support, and for teaching us how to use and make it better. Introduction | xv
23.
CHAPTER 1 Introducing Angular Ourexpectations of what we can perform on the web (and by web here, I mean both desktop as well as the mobile web) has increased to the point where what used to be full-fledged native desktop applications are run on the browser. Web applications now resemble desktop native applications in scope and complexity, which also results in added complexity as a developer. Furthermore, Single-Page Applications (SPAs) have become a very common choice in building out frontend experiences, as they allow for great customer experiences in terms of speed and responsiveness. Once the initial application has loaded into a cus‐ tomer’s browser, further interactions only have to worry about loading the additional data needed, without reloading the entire page as was the norm with server-side ren‐ dered pages of the past. AngularJS was started to first bring structure and consistency to single-page web application development, while providing a way to quickly develop scalable and maintainable web applications. In the time since it was released, the web and brows‐ ers have moved forward by leaps and bounds, and some of the problems that Angu‐ larJS was solving weren’t as relevant anymore. Angular then was basically a completely new rewritten version of the framework, built for the new-age web. It leveraged a lot of the newer advances, from modules to web components, while improving the existing features of AngularJS, like depend‐ ency injection and templating. From now on, when I say AngularJS, I refer to the original Angu‐ larJS framework, the 1.0 version. Whenever I mention Angular, it refers to the newer framework, from 2.0 onward. This is primarily because Angular 2.0 onward does not predicate itself to using only JavaScript, but also supports writing applications in TypeScript. 1
24.
Why Angular Angular asa framework provides a few significant advantages while also providing a common structure for developers on a team to work with. It allows us to develop large applications in a maintainable manner. We will dig into each one of these in more detail in the following chapters: Custom components Angular allows you to build your own declarative components that can pack functionality along with its rendering logic into bite-sized, reusable pieces. It also plays well with web components. Data binding Angular allows you to seamlessly move your data from your core JavaScript code to the view, and react to view events without having to write the glue code your‐ self. Dependency injection Angular allows you to write modular services, and have them injected wherever they are needed. This greatly improves the testability and reusability of the same. Testing Tests are first-class citizens, and Angular has been built from the ground up with testability in mind. You can (and should!) test every part of your application. Comprehensive Angular is a full-fledged framework, and provides out-of-the-box solutions for server communication, routing within your application, and more. Angular as a framework has adopted semantic versioning for all new releases. Furthermore, the core team has an aggressive road‐ map, with a new major release planned every six months. Thus, what started off as Angular 2 is now referred to as just Angular, since we don’t want to call them Angular 2, Angular 4, Angular 5, and so on. That said, unlike AngularJS to Angular, upgrading between ver‐ sions of Angular (say 2 to 4, etc.) is an incremental step, and more often than not an almost trivial upgrade. So you don’t need to worry about having to do a major upgrade every few months with drastic code changes. What This Book Will Not Cover While Angular as a framework is quite large, the community around it is even larger. A lot of great features and options for use with Angular in fact stem from this 2 | Chapter 1: Introducing Angular
25.
community. This makeslife harder as an author to figure out how to write a book that preps you, the reader, as an Angular developer, while still limiting the scope to what I think are the essentials. To that extent, while Angular can be extended in so many ways, from writing native mobile apps using Angular (see NativeScript), rendering your Angular application on the server (see Angular Universal), using Redux as a first-class option in Angular (multiple options; see ngrx), and many more, the initial version of the book will only focus on the core Angular platform and all the capabilities it provides. It will also strive to focus on the more common cases rather than cover every single feature and capability of Angular, as such a book would run into thousands of pages. The intention is to focus on the parts that will be necessary and useful to all Angular developers, rather than focus on bits and parts that would be useful to a subset. Getting Started with Your Development Environment Angular expects you to do a fair bit of groundwork to be able to develop seamlessly on your computer. Certain prerequisites need to be installed that we will cover in this section. Node.js While you will never be coding in Node.js, Angular uses Node.js as its base for a large part of its build environment. Thus, to get started with Angular, you will need to have Node.js installed on your environment. There are multiple ways to install Node.js, so please refer to the Node.js Download Page for more instructions. On macOS, installing Node.js through Homebrew has been known to cause some issues. So try installing it directly if you run into any problems. You need to install version 6.9.0 or above of Node.js, and version 3.0.0 or above of npm. You can confirm your versions after installing by running the following commands: node --version npm --v TypeScript TypeScript adds a set of types to the JavaScript code that we write, allowing us to write JavaScript that is easier to understand, reason about, and trace. It ensures that the latest proposed ECMAScript features are also available at the tip of our fingers. At Getting Started with Your Development Environment | 3
26.
the end ofthe day, all your TypeScript code compiles down to JavaScript that can run easily in any environment. TypeScript is not mandatory for developing an Angular application, but it is highly recommended, as it offers some syntactic sugar, as well as makes the codebase easier to understand and maintain. In this book, we will be using TypeScript to develop Angular applications. TypeScript is installed as an NPM package, and thus can be simply installed with the following command: npm install -g typescript Make sure you install at least version 2.4.0 or above. While we will be covering most of the basic features/concepts that we use from Type‐ Script, it is always a good idea to learn more from the official TypeScript documenta‐ tion. Angular CLI Unlike AngularJS, where it was easy to source one file as a dependency and be up and running, Angular has a slightly more complicated setup. To this extent, the Angular team has created a command-line interface (CLI) tool to make it easier to bootstrap and develop your Angular applications. As it significantly helps making the process of development easier, I recommend using it at the very least for your initial projects until you get the hang of all the things it does and are comfortable doing it yourself. In this book, we will cover both the CLI command as well as the actions it performs underneath, so that you get a good understanding of all the changes needed. Installing the latest version (1.7.3 at the time of writing this book) is as simple as run‐ ning the following command: npm install -g @angular/cli If you are scratching your head at this newfangled naming conven‐ tion for Angular packages, the new syntax is a feature of NPM called scoped packages. It allows packages to be grouped together within NPM under a single folder. You can read more here. Once installed, you can confirm if it was successful by running the following command: ng --version 4 | Chapter 1: Introducing Angular
27.
Getting the Codebase Allthe examples from this book, along with the exercises and the final solution, are hosted as a Git repository. While it is not mandatory to download this, you can choose to do so if you want a reference or want to play around with the samples in this book. You can do so by cloning the Git repository by running the following command: git clone https://github.com/shyamseshadri/angular-up-and-running.git This will create a folder called angular-up-and-running in your current working direc‐ tory with all the necessary examples. Within this directory you’ll find subfolders con‐ taining the examples, organized by chapter. Conclusion At this point, we are all set up with our development environment and are ready to start developing Angular applications. We have installed Node.js, TypeScript, as well as the Angular CLI and understand the need and use of each. In the next chapter, we will finally get our hands dirty building our first Angular application and understanding some of the basic terms and concepts of Angular. Conclusion | 5
29.
CHAPTER 2 Hello Angular Inthe previous chapter, we got a very quick overview of Angular and its features, as well as a step-by-step guide on how to set up our local environment for developing any Angular application. In this chapter, we will go through the various parts of an Angular application by creating a very simple application from scratch. Through the use of this application, we will cover some of the basic terminologies and concepts like modules, components, data and event binding, and passing data to and from components. We will start with a very simple stock market application, which allows us to see a list of stocks, each with its own name, stock code, and price. During the course of this chapter, we will see how to package rendering a stock into an individual, reusable component, and how to work with Angular event and data binding. Starting Your First Angular Project As mentioned in the previous chapter, we will heavily rely on the Angular CLI to help us bootstrap and develop our application. I will assume that you have already fol‐ lowed the initial setup instructions in the previous chapter and have Node.js, Type‐ Script, and the Angular CLI installed in your development environment. Creating a new application is as simple as running the following command: ng new stock-market When you run this command, it will automatically generate a skeleton application under the folder stock-market with a bunch of files, and install all the necessary dependencies for the Angular application to work. This might take a while, but even‐ tually, you should see the following line in your terminal: Project 'stock-market' successfully created. 7
30.
Congratulations, you havejust created your first Angular application! While we created our first application with the vanilla Angular CLI command, the ng new command takes a few arguments that allow you to customize the application generated to your preference. These include: • Whether you want to use vanilla CSS or SCSS or any other CSS framework (for example, ng new --style=scss) • Whether you want to generate a routing module (for example, ng new --routing); we’ll discuss this further in Chapter 11. • Whether you want inline styles/templates • Whether you want a common prefix to all components (for example, to prefix acme to all components, ng new --prefix=acme) And much more. It’s worth exploring these options by running ng help once you are a bit more familiar with the Angular framework to decide if you have specific preferences one way or the other. Understanding the Angular CLI While we have just created our first Angular application, the Angular CLI does a bit more than just the initial skeleton creation. In fact, it is useful throughout the devel‐ opment process for a variety of tasks, including: • Bootstrapping your application • Serving the application • Running the tests (both unit and end-to-end) • Creating a build for distribution • Generating new components, services, routes and more for your application Each of these corresponds to one or more Angular CLI commands, and we will cover each one as and when we need or encounter them, instead of trying to cover each command and its uses upfront. Each command provides further flexibility with a variety of arguments and options, making the Angular CLI truly diverse and capable for a wide variety of uses. 8 | Chapter 2: Hello Angular
31.
Running the Application Nowthat we have generated our application, the next part is to run it so that we can see our live running application in the browser. There are technically two ways to run it: • Running it in development mode, where the Angular CLI compiles the changes as it happens and refreshes our UI • Running it in production mode, with an optimal compiled build, served via static files For now, we will run it in development mode, which is as simple as running ng serve from the root folder of the generated project, which is the stock-market folder in this case. After a little bit of processing and compilation, you should see something like the following in your terminal: ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** Date: 2018-03-26T10:09:18.869Z Hash: 0b730a52f97909e2d43a Time: 11086ms chunk {inline} inline.bundle.js (inline) 3.85 kB [entry] [rendered] chunk {main} main.bundle.js (main) 17.9 kB [initial] [rendered] chunk {polyfills} polyfills.bundle.js (polyfills) 549 kB [initial] [rendered] chunk {styles} styles.bundle.js (styles) 41.5 kB [initial] [rendered] chunk {vendor} vendor.bundle.js (vendor) 7.42 MB [initial] [rendered] webpack: Compiled successfully. The preceding output is a snapshot of all the files that the Angular CLI generates in order for your Angular application to be served successfully. It includes the main.bundle.js, which is the transpiled code that is specific to your application, and the vendor.bundle.js, which includes all the third-party libraries and frameworks you depend on (including Angular). styles.bundle.js is a compilation of all the CSS styles that are needed for your application, while polyfills.bundle.js includes all the polyfills needed for supporting some capabilities in older browsers (like advanced ECMA‐ Script features not yet available in all browsers). Finally, inline.bundle.js is a tiny file with webpack utilities and loaders that is needed for bootstrapping the application. ng serve starts a local development server on port 4200 for you to hit from your browser. Opening http://localhost:4200 in your browser should result in you seeing the live running Angular application, which should look like Figure 2-1. Understanding the Angular CLI | 9
32.
Figure 2-1. HelloAngular application in the browser You can actually leave the ng serve command running in the ter‐ minal, and continue making changes. If you have the application opened in your browser, it will automatically refresh each time you save your changes. This makes the development quick and itera‐ tive. 10 | Chapter 2: Hello Angular
33.
In the followingsection, we will go into a bit more detail about what exactly hap‐ pened under the covers to see how the generated Angular application works and what the various pieces are. Basics of an Angular Application At its core, any Angular application is still a Single-Page Application (SPA), and thus its loading is triggered by a main request to the server. When we open any URL in our browser, the very first request is made to our server (which is running within ng serve in this case). This initial request is satisfied by an HTML page, which then loads the necessary JavaScript files to load both Angular as well as our application code and templates. One thing to note is that although we develop our Angular application in TypeScript, the web application works with transpiled JavaScript. The ng serve command is responsible for translating our TypeScript code into JavaScript for the browser to load. If we look at the structure the Angular CLI has generated, it is something like this: stock-market +----e2e +----src +----app +----app.component.css +----app.component.html +----app.component.spec.ts +----app.component.ts +----app.module.ts +----assets +----environments +----index.html +----main.ts +----.angular-cli.json Root component Main module Root HTML Entry point Angular CLI config There are a few more files than listed here in the stock-market folder, but these are the major ones we are going to focus on in this chapter. In addition, there are unit tests, Basics of an Angular Application | 11
34.
end-to-end (e2e) tests,the assets that support our application, configuration specific to various environments (dev, prod, etc.), and other general configuration that we will touch upon in Chapters 5, 10, and 12. Root HTML—index.html If you take a look at the index.html file, which is in the src folder, you will notice that it looks very clean and pristine, with no references to any scripts or dependencies: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>StockMarket</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> Root component for our Angular application The only thing of note in the preceding code is the <app-root> element in the HTML, which is the marker for loading our application code. What about the part that loads the core Angular scripts and our application code? That is inserted dynamically at runtime by the ng serve command, which combines all the vendor libraries, our application code, the styles, and inline templates each into individual bundles and injects them into index.html to be loaded as soon as the page renders in our browser. The Entry Point—main.ts The second important part of our bootstrapping piece is the main.ts file. The index.html file is responsible for deciding which files are to be loaded. The main.ts file, on the other hand, identifies which Angular module (which we will talk a bit more about in the following section) is to be loaded when the application starts. It can also change application-level configuration (like turning off framework-level asserts and verifications using the enableProdMode() flag), which we will cover in Chap‐ ter 12: import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; 12 | Chapter 2: Hello Angular
35.
import { environment} from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.log(err)); Bootstrap the main AppModule Most of the code in the main.ts file is generic, and you will rarely have to touch or change this entry point file. Its main aim is to point the Angular framework at the core module of your application and let it trigger the rest of your application source code from that point. Main Module—app.module.ts This is where your application-specific source code starts from. The application mod‐ ule file can be thought of as the core configuration of your application, from loading all the relevant and necessary dependencies, declaring which components will be used within your application, to marking which is the main entry point component of your application: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } NgModule TypeScript annotation to mark this class definition as an Angular module Declarations marking out which components and directives can be used within the application Basics of an Angular Application | 13
36.
Importing other modulesthat provide functionality needed in the application The entry point component for starting the application This is our first time dealing with a TypeScript-specific feature, which are decorators (you can think of them as annotations). Dec‐ orators allow us to decorate classes with annotations and properties as well as meta-functionality. Angular heavily leverages this TypeScript feature across the board, such as using decorators for modules, components, and more. You can read more about TypeScript decorators in the official doc‐ umentation. We will go over the details of each of these sections in the following chapters, but at its core: declarations The declarations block defines all the components that are allowed to be used in the scope of the HTML within this module. Any component that you create must be declared before it can be used. imports You will not create each and every functionality used in the application, and the imports array allows you to import other Angular application and library mod‐ ules and thus leverage the components, services, and other capabilities that have already been created in those modules. bootstrap The bootstrap array defines the component that acts as the entry point to your application. If the main component is not added here, your application will not kick-start, as Angular will not know what elements to look for in your index.html. You usually end up needing (if you are not using the CLI for any reason!) to modify this file if and only if you add new components, services, or add/integrate with new libraries and modules. Root Component—AppComponent We finally get to the actual Angular code that drives the functionality of the applica‐ tion, and in this case, it is the main (and only) component we have, the AppCompo nent. The code for it looks something like this: 14 | Chapter 2: Hello Angular
37.
import { Component} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; } The DOM selector that gets translated into an instance of this component The HTML template backing this component—in this case, the URL to it Any component-specific styling, again pointing to a separate file in this case The component class with its own members and functions A component in Angular is nothing but a TypeScript class, decorated with some attributes and metadata. The class encapsulates all the data and functionality of the component, while the decorator specifies how it translates into the HTML. The app-selector is a CSS selector that identifies how Angular finds this particular component in any HTML page. While we generally use element selectors (app-root in the preceding example, which translates to looking for <app-root> elements in the HTML), they can be any CSS selector, from a CSS class to an attribute as well. The templateUrl is the path to the HTML used to render this component. We can also use inline templates instead of specifying a templateUrl like we have done in the example. In this particular case, the template we are referring to is app.compo‐ nent.html. styleUrls is the styling counterpart to the template, encapsulating all the styles for this component. Angular ensures that the styles are encapsulated, so you don’t have to worry about your CSS classes from one component affecting another. Unlike tem plateUrl, styleUrls is an array. The component class itself finally encapsulates all the functionality backing your component. It makes it easy to think of the responsibilities of the component class as twofold: • Load and hold all the data necessary for rendering the component • Handle and process any events that may arise from any element in the component Basics of an Angular Application | 15
38.
The data inthe class will drive what can be displayed as part of the component. So let’s take a look at what the template for this component looks like: <h1> {{title}} </h1> Data-bound title from the component Our HTML is as simple as can be for the component. All it has is one element, which is data-bound to a field in our component class. The double-curly ({{ }}) syntax is an indication to Angular to replace the value between the braces with the value of the variable from the corresponding class. In this case, once the application loads, and the component is rendered, the {{title}} will be replaced with the text app works!. We will talk in more detail about data binding in “Understanding Data Binding” on page 19. Creating a Component So far, we have dealt with the basic skeleton code that the Angular CLI has generated for us. Let’s now look at adding new components, and what that entails. We will use the Angular CLI to generate a new component, but look underneath the covers to see what steps it takes. We will then walk through some very basic common tasks we try to accomplish with components. Steps in Creating New Components Using the Angular CLI, creating a new component is simply running a simple com‐ mand. We will first try creating a stock widget, which displays the name of the stock, its stock code, the current price, and whether it has changed for the positive or nega‐ tive. We can simply create a new stock-item by running the following command from the main folder of the application: ng generate component stock/stock-item There are a few interesting things to note here: • The Angular CLI has a command called generate, which can be used to generate components (like we did in the preceding example), and also to generate other Angular elements, such as interfaces, services, modules, and more. • With the target type, we also specify the name (and the folder) within which the component has to be generated. Here, we are telling the Angular CLI to generate 16 | Chapter 2: Hello Angular
39.
a component calledstock-item within a folder called stock. If we don’t specify stock, it will create a component called stock-item in the app folder itself. The command will generate all the relevant files for a new component, including: • The component definition (named stock-item.component.ts) • The corresponding template definition (named stock-item.component.html) • The styles for the component (in a file named stock-item.component.css) • The skeleton unit tests for the component (named stock-item.component.spec.ts) In addition, it updated the original app module that we saw earlier so that our Angu‐ lar application recognizes the new module. This is the recommended convention to follow whenever you are working with components: • The filename starts with the name of the item you are creating • This is followed by the type of element it is (in this case, a component) • Finally, we have the relevant extension This allows us to both group and easily identify relevant and related files in a simple manner. When you run the command, you should see something like this: create src/app/stock/stock-item/stock-item.component.css create src/app/stock/stock-item/stock-item.component.html create src/app/stock/stock-item/stock-item.component.spec.ts create src/app/stock/stock-item/stock-item.component.ts update src/app/app.module.ts The source for the component, HTML, and the CSS remain pretty much barebones, so I won’t repeat that here. What is important is how this new component that we create is hooked up and made available to our Angular application. Let’s take a look at the modified app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { StockItemComponent } from './stock/stock-item/stock-item.component'; @NgModule({ declarations: [ AppComponent, StockItemComponent ], Creating a Component | 17
40.
imports: [ BrowserModule ], providers: [], bootstrap:[AppComponent] }) export class AppModule { } Importing the newly created stock-item component Adding the new component to the declarations section In the application module, we have to ensure that the new component is imported and added to the declarations array, before we can start using it in our Angular application. Using Our New Component Now that we have created a new component, let’s see how we can use it in our appli‐ cation. We will now try to use this skeleton in the app component. First, take a look at the generated stock-item.component.ts file: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { constructor() { } ngOnInit() { } } The selector for using this component. Note it is prefixed with app, which is added by the Angular CLI by default unless otherwise specified. The component has no data and does not provide any functionality at this point; it simply renders the template associated with it. The template at this point is also triv‐ ial, and just prints out a static message. To use this component in our application, we can simply create an element that matches the selector defined anywhere inside our main app component. If we had more components and a deeper hierarchy of components, we could choose to use it in any of their templates as well. So let’s replace most of the placeholder content in 18 | Chapter 2: Hello Angular
41.
app.component.html with thefollowing, so that we can render the stock-item component: <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> <app-stock-item></app-stock-item> </div> Adding our stock-item component All it takes is adding the <app-stock-item></app-stock-item> to our app.compo‐ nent.html file to use our component. We simply create an element using the selector we defined in our component. Then when the application loads, Angular recognizes that the element refers to a component, and triggers the relevant code path. When you run this (or if your ng serve is still running), you should see both the original "app works" along with a new "stock-item works" in the UI. Understanding Data Binding Next, let’s focus on getting some data and figuring out how to display it as part of our component. What we are trying to build is a stock widget, which will take some stock information, and render it accordingly. Let’s assume that we have a stock for a company named Test Stock Company, with a stock code of TSC. Its current price is $85, while the previous price it traded at was $80. In the widget, we want to show both the name and its code, as well as the current price, the percentage change since last time, and highlight the price and percentage change in green if it is an increment, or red if it is a decrement. Let’s walk through this step by step. First, we will make sure we can display the name and code in the widget (we will hardcode the information for now, and we will build up the example to get the data from a different source later). We would change our component code (the stock-item.component.ts file) as follows: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { public name: string; public code: string; Creating a Component | 19
42.
public price: number; publicpreviousPrice: number; constructor() { } ngOnInit() { this.name = 'Test Stock Company'; this.code = 'TSC'; this.price = 85; this.previousPrice = 80; } } Implement OnInit interface from Angular, which gives us a hook to when the component is initialized Definition of the various fields we will want to access from the HTML OnInit function that is triggered when a component is initialized Initializing the values for each of the fields Angular gives us hooks into the lifecycle of a component to let us take certain actions when a component is initialized, when its view is rendered, when it is destroyed, and so on. We’ve extended our trivial component with a few notable things: OnInit Angular’s OnInit hook is executed after the component is created by the Angular framework, after all the data fields are initialized. It is generally recommended to do any initialization work of a component in the OnInit hook, so that it makes it easier to test the functionality of the rest of the component without necessarily triggering the initialization flow every time. We will cover the remaining lifecycle hooks in Chapter 4. ngOnInit When you want to hook on the initialization phase of a component, you need to implement the OnInit interface (as in the example) and then implement the ngOnInit function in the component, which is where you write your initializa‐ tion logic. We have initialized the basic information we need to render our stock widget in the ngOnInit function. Class member variables We have declared a few public variables as class instance variables. This informa‐ tion will be used to render our template. Now, let’s change the template (the stock-item.component.html file) to start rendering this information: 20 | Chapter 2: Hello Angular
43.
<div class="stock-container"> <div class="name"><h3>{{name}}</h3>- <h4>({{code}})</h4></div> <div class="price">$ {{price}}</div> </div> and its corresponding CSS (the stock-item.component.css file), to make it look nice: .stock-container { border: 1px solid black; border-radius: 5px; display: inline-block; padding: 10px; } .stock-container .name h3, .stock-container .name h4 { display: inline-block; } Note that the CSS is purely from a visual perspective, and is not needed nor impacts our Angular application. You could skip it completely and still have a functional application. Once we make these changes and refresh our application, we should see something like Figure 2-2 in our browser. Figure 2-2. Angular app with stock component We have just used one fundamental building block from Angular to render our data from our component into the HTML. We use the double-curly notation ({{ }}), which is also known as interpolation. Interpolation evaluates the expression between the curly braces as per the component backing it, and then renders the result as a Creating a Component | 21
44.
string in placein the HTML. In this case, we render the name, code, and the price of the stock using interpolation. This picks up the values of name, code, and price, and then replaces the double-curly expression with its value, thus rendering our UI. This is Angular’s one-way data binding at work. One-way data binding simply refers to Angular’s capability to automatically update the UI based on values in the compo‐ nent, and then keeping it updated as the value changes in the component. Without one-way binding, we would have to write code to take the value from our component, find the right element in HTML, and update its value. Then we would have to write listeners/watchers to keep track of when the value in the component changes, and then change the value in the HTML at that time. We can get rid of all of this extra code because of data binding. In this particular case, we are binding to simple variables, but it is not necessarily restricted to simple variables. The expressions can be slightly more complex. For example, we could render the same UI by changing the binding expression as follows in stock-item.component.html: <div class="stock-container"> <div class="name">{{name + ' (' + code + ')'}}</div> <div class="price">$ {{price}}</div> </div> In this case, we replaced our multiple heading elements with a single div. The interpo‐ lation expression is now a combination of both the name and the code, with the code surrounded by parentheses. Angular will evaluate this like normal JavaScript, and return the value of it as a string to our UI. Understanding Property Binding So far, we used interpolation to get data from our component code to the HTML. But Angular also provides a way to bind not just text, but also DOM element properties. This allows us to modify the content and the behavior of the HTML that is rendered in the browser. For example, let’s try to modify our stock widget to highlight the price in red if the price is less than the previous price, and in green if it is equal to or more than the previous price. We can first change our component (the stock-item.component.ts) to precalculate if the difference is positive or negative like so: 22 | Chapter 2: Hello Angular
45.
import { Component,OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { public name: string; public code: string; public price: number; public previousPrice: number; public positiveChange: boolean; constructor() { } ngOnInit() { this.name = 'Test Stock Company'; this.code = 'TSC'; this.price = 85; this.previousPrice = 80; this.positiveChange = this.price >= this.previousPrice; } } In this code, we added a new public variable called positiveChange, which is of type boolean, and then set the value based on comparing the current price with the previ‐ ous price. This gives us a singular boolean value that we can use to decide whether to highlight the price in red or green. Next, let’s add some classes in the stock-item.component.css file to allow for changing the color of the text: .stock-container { border: 1px solid black; border-radius: 5px; display: inline-block; padding: 10px; } .positive { color: green; } .negative { color: red; } We simply added two classes, positive and negative, which change the color of the text to green and red, respectively. Now let’s tie this together to see how we can use this information and classes in our stock-item.component.html file: Creating a Component | 23
46.
<div class="stock-container"> <div class="name">{{name+ ' (' + code + ')'}}</div> <div class="price" [class]="positiveChange ? 'positive' : 'negative'">$ {{price}}</div> </div> We have added one new binding on the price div element, which reads as: [class]="positiveChange ? 'positive' : 'negative'" This is the Angular syntax for property binding, which binds the value of the expres‐ sion to the DOM property between the square brackets. The [] is the general syntax that can be used with any property on an element to bind one-way from the compo‐ nent to the UI. In this particular case, we are telling Angular to bind to the class property of the DOM element to the value of the expression. Angular will evaluate it like a normal JavaScript expression, and assign the value (positive in this case) to the class property of the div element. When you bind to the class property like we did in the example, note that it overrides the existing value of the property. In our example, the "price" class is replaced with the class "positive", instead of appending to the existing value of the property. You can notice this for yourself if you inspect the rendered HTML in the browser. Be careful about this if you bind directly to the class property. If the value of the variable positiveChange in the component changes, Angular will automatically re-evaluate the expression in the HTML and update it accordingly. Try changing the price so that there is a negative change and then refresh the UI to make sure it works. Notice that we have been explicitly referring to the data binding working with DOM properties, and not HTML attributes. The following sidebar goes into more detail on the difference between the two, and why it is important to know and understand as you work on Angular. But simplifying it, Angular data binding only works with DOM properties, and not with HTML attributes. HTML Attribute Versus DOM Property: What’s the Difference? As mentioned, when we work with data binding in Angular, we aren’t working with HTML attributes but rather DOM properties. Attributes are defined by HTML, while properties are defined by the Document Object Model. Though some attributes (like ID and class) directly map to DOM properties, others may exist on one side but not the other. 24 | Chapter 2: Hello Angular
47.
But more importantly,the distinction between the two is that HTML attributes are generally used for initialization of a DOM element, but after that, they have no pur‐ pose or effect on the underlying element. Once the element is initialized, its behavior is controlled by the DOM properties from then on. For example, consider the input HTML element. If we bootstrap our HTML with something like: <input type="text" value="foo"/> this initializes an input DOM element, with the initial value of the DOM property value to be set to foo. Now let’s assume we type something in the text box, say bar. At this point: • If we do input.getAttribute('value'), it would return foo, which was the attribute value we used to initialize the HTML. • If we do input.value, we will get the current value of the DOM property, which is bar. That is, the attribute value is used to boostrap and set the initial value of the HTML DOM element, but after that, it is the DOM property that drives the behavior. If you inspect the HTML, you will see that it is still the initial HTML we provided, and does not update either. In Angular, we thus bind to the DOM property, and not to the HTML attributes. Whenever we think about one-way binding from the component to the UI, we should always keep this in mind! Just like we did for the class property, depending on the use case, we can actually bind to other HTML properties like the src property of an img tag, or the disabled property of input and button. We will cover this in more depth in the next chapter. We will also cover a simpler and more specific way of binding CSS classes in the next chapter as well. Understanding Event Binding So far, we have worked on using the data in our component to both render values and change the look and feel of our component. In this section, we will start understand‐ ing how to handle user interactions, and work with events and event binding in Angular. Say we wanted to have a button that allows users to add the stock to their list of favor‐ ite stocks. Generally, with a button like this, when the user clicks it, we would want to make some server call and then process the result. So far, since we are working with Creating a Component | 25
48.
very simple examples,let’s just say we wanted to handle this click and get a hook to it in our component. Let’s see how we might accomplish that. First, we can change our component code in stock-item.component.ts to add a func‐ tion toggleFavorite, which should be triggered each time the click happens from the UI: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { public name: string; public code: string; public price: number; public previousPrice: number; public positiveChange: boolean; public favorite: boolean; constructor() { } ngOnInit() { this.name = 'Test Stock Company'; this.code = 'TSC'; this.price = 85; this.previousPrice = 80; this.positiveChange = this.price >= this.previousPrice; this.favorite = false; } toggleFavorite() { console.log('We are toggling the favorite state for this stock'); this.favorite = !this.favorite; } } We have added a new public boolean member variable called favorite, which is ini‐ tialized with a false value. We then added a new function called toggleFavorite(), which simply flips the boolean value of favorite. We are also printing a log in the console to ensure this is getting triggered. Now, let’s update the UI to use this concept of a favorite and also allow users to tog‐ gle the state: 26 | Chapter 2: Hello Angular
49.
<div class="stock-container"> <div class="name">{{name+ ' (' + code + ')'}}</div> <div class="price" [class]="positiveChange ? 'positive' : 'negative'">$ {{price}}</div> <button (click)="toggleFavorite()" [disabled]="favorite">Add to Favorite</button> </div> We have added a new button in the stock-item.component.html file to allow users to click and add the stock to their favorite set. We are using the data-binding concept from the previous section on the disabled property. Thus, we are disabling the but‐ ton based on the boolean value favorite. If favorite is true, the button will be dis‐ abled, and if it is false, the button will be enabled. Thus, by default, the button is enabled. The other major thing we have on the element is this fragment: (click)="toggleFavorite()" This syntax is called event binding in Angular. The left part of the equals symbol refers to the event we are binding to. In this case, it is the click event. Just like how the square-bracket notation refers to data flowing from the component to the UI, the parentheses notation refers to events. And the name between the parentheses is the name of the event we care about. In this case, we are telling Angular that we are interested in the click event on this element. The right part of the equals symbol then refers to the template statement that Angular should execute whenever the event is triggered. In this case, we want it to execute the new function we created, toggleFavorite. When we run this application in our browser, we can see the new button. Clicking it would render something like Figure 2-3. Notice the other interesting thing, which is Angular data binding at play. When we click the button, our toggleFavorite function is executed. This flips the value of favorite from false to true. This in turn triggers the other Angular binding, which is the disabled property of the button, thus disabling the button after the first click. We don’t have to do anything extra to get these benefits, which is the beauty of data binding. Creating a Component | 27
50.
Figure 2-3. Handlingevents in an Angular app There are times when we might also care about the actual event triggered. In those cases, Angular gives you access to the underlying DOM event by giving access to a special variable $event. You can access it or even pass it to your function as follows: 28 | Chapter 2: Hello Angular
51.
<div class="stock-container"> <div class="name">{{name+ ' (' + code + ')'}}</div> <div class="price" [class]="positiveChange ? 'positive' : 'negative'">$ {{price}}</div> <button (click)="toggleFavorite($event)" [disabled]="favorite">Add to Favorite</button> </div> In the HTML, we simply add a reference to the variable $event, and pass it in as an argument to our toggleFavorite function. We can now refer to it in our component as follows: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { public name: string; public code: string; public price: number; public previousPrice: number; public positiveChange: boolean; public favorite: boolean; constructor() { } ngOnInit() { this.name = 'Test Stock Company'; this.code = 'TSC'; this.price = 85; this.previousPrice = 80; this.positiveChange = this.price >= this.previousPrice; this.favorite = false; } toggleFavorite(event) { console.log('We are toggling the favorite state for this stock', event); this.favorite = !this.favorite; } } When you run the application, you will see that when you click the button, your con‐ sole log now appends the actual MouseEvent that was triggered, in addition to our previous code. In a similar manner, we can easily hook onto other standard DOM events that are triggered, like focus, blur, submit, and others like them. Creating a Component | 29
52.
Why Angular Shiftedto Property and Event Binding Anyone who has worked on AngularJS would be wondering why the framework developers decided to do such a major breaking change when they created Angular. The binding syntax has changed drastically, as well as the directives and symbols used. In AngularJS, we had ng-bind, ng-src, and the like for binding from our con‐ trollers to the UI, and directives like ng-click and ng-submit for handling events. This meant that any time there was a new event or property that we wanted to bind to in AngularJS, we would end up writing a wrapper directive that would do the work of translating from AngularJS to the inner workings and vice versa. The other problem with the AngularJS syntax was that there was no clear differentia‐ tion between data flowing from our controller to the UI or from the UI to the con‐ troller. Both follow the same syntax, which made understanding the HTML sometimes difficult, and required developers to understand each directive first. In Angular, we instead rely on core DOM properties and events for binding. This means that if a property or event exists as per the HTML standards, we can bind to it. This also makes it very easy to work with web components that expose proper prop‐ erties and events, as Angular works with them simply out of the box, without needing to write any additional code. This has also made obsolete the tons of AngularJS direc‐ tives from the past, such as ng-click, ng-submit, and so on, and makes it easier for any web developer to quickly understand and work with Angular. You don’t have to spend as much time learning Angular-specific knowledge. Furthermore, the square bracket and parentheses notation also makes it very obvious about the flow of data. Any time you see the square bracket notation, you can be assured that it is data flowing from the component into the HTML. Any time you see the parentheses notation, you are guaranteed that it refers to an event and flows from a user action to the component. Using Models for Cleaner Code The last part of this chapter covers something that is more of a best practice, but it is worth adopting—especially as we aim to build large, maintainable web applications using Angular. We want to use encapsulation to ensure that our components don’t work with lower-level abstractions and properties, like we did previously where the stock widget gets an individual name, price, etc. At the same time, we want to lever‐ age TypeScript to make it easier to understand and reason about our application and its behavior. To this extent, we should ideally model our stock itself as a type in Type‐ Script, and leverage that instead. 30 | Chapter 2: Hello Angular
53.
The way wewould do it in TypeScript is to define an interface or a class with the defi‐ nition for what belongs in a stock, and use that consistently throughout our applica‐ tion. In this case, since we might want additional logic in addition to just the values (calculating whether the price differential is positive or not, for example), we can use a class. We can use the Angular CLI to quickly generate a skeleton class for us, by running: ng generate class model/stock This will generate an empty skeleton file called stock.ts in a folder called model. We can go ahead and change it as follows: export class Stock { favorite: boolean = false; constructor(public name: string, public code: string, public price: number, public previousPrice: number) {} isPositiveChange(): boolean { return this.price >= this.previousPrice; } } This gives us a nice encapsulation while we work with stocks across our application. Note that we didn’t actually define the variables name, code, and so on as properties of the class. This is because we are using TypeScript’s syntactic sugar to automatically create the corresponding properties based on the constructor arguments by using the public keyword. To learn more about TypeScript classes, refer to the official docu‐ mentation. In short, we have created a class with five properties, four coming through the constructor and one autoinitialized. Let’s see how we might use this now in our component: import { Component, OnInit } from '@angular/core'; import { Stock } from '../../model/stock'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { public stock: Stock; constructor() { } ngOnInit() { Creating a Component | 31
54.
this.stock = newStock('Test Stock Company', 'TSC', 85, 80); } toggleFavorite(event) { console.log('We are toggling the favorite state for this stock', event); this.stock.favorite = !this.stock.favorite; } } In stock-item.component.ts, we imported our new model definition at the top, and then replaced all the individual member variables with one variable of type Stock. This simplified the code in the component significantly, and encapsulated all the logic and underlying functionality within a proper TypeScript type. Now let’s see how stock-item.component.html changes to accommodate this change: <div class="stock-container"> <div class="name">{{stock.name + ' (' + stock.code + ')'}}</div> <div class="price" [class]="stock.isPositiveChange() ? 'positive' : 'negative'"> $ {{stock.price} </div> <button (click)="toggleFavorite($event)" [disabled]="stock.favorite">Add to Favorite</button> </div> We have made a few changes in the HTML for our stock item. First, most of our ref‐ erences to the variable are now through the stock variable, instead of directly access‐ ing the variables in the component. So name became stock.name, code became stock.code, and so on. Also, one more thing of note: our class property binding now refers to a function instead of a variable. This is acceptable, as a function is also a valid expression. Angu‐ lar will just evaluate the function and use its return value to determine the final expression value. Conclusion In this chapter, we started building our very first Angular application. We learned how to bootstrap our Angular application, as well as understand the various pieces that the Angular skeleton application generates and their needs and uses. We then created our very first component, and looked at the steps involved in hooking it up to our application. Following that, we added some very basic data to our component, and then used that to understand how basic Angular data binding works, using both interpolation as well as property binding. We then looked at how event binding works, and handled 32 | Chapter 2: Hello Angular
Fig. 280.—Fine Sectionthrough Truffle. a. Asci filled with spores; b. Mycelia, × 250. “Frank stated, as the result of his experimental research, that seedling forest-trees cannot be grown in sterilised soil, where their roots are prevented from forming mycorhiza; and he concluded that the fungus conveys organic materials to the roots, which it obtains by breaking down the leaf-mould and decaying plant remains, together with water and minerals from the soil, and plays the especial part of a nitrogen-catching apparatus. In return for this import service the root pays a tax to the fungus by sparing it certain of its tissue contents. It is a curious fact then that the mycorhiza is only formed where humus or vegetable mould abounds.” These instructive investigations offer an intelligible explanation of the growth of that well-known subterranean fungus, the truffle (Tuber cibarium), the microscopic appearances of a section of which
57.
formed the subjectof a paper I contributed to “The Popular Science Review” some years ago (1862). The fungus, as will be seen by the fine section cut through a truffle, Fig. 280, consists of flocculent filaments, which in the first instance cover the ground at the fall of the leaf in autumn, under oak or beech trees, the hyphæ of which penetrate the ground, through the humid soil to the root-hairs of the tree. Filaments (mycelia) are again given off which terminate in asci or sacs filled with minute spores of about 1⁄2500th of an inch in size, while the interspaces are filled up by mycelia, that become consolidated into a firm nut-like body. What happens, then, is this: Trees and plants with normal roots and root-hairs, when growing in ordinary soil, can adapt their roots to life in a soil heavily charged with humus only by contracting symbiotic association with the fungus and paying the tax demanded by the latter in return for its supplies and services. If this adaptation is impossible, and no other suitable variation is evolved, such trees cannot grow in such soils. The physiological relations of the root to the fungus must be different in details in the case of non-green, purely saprophytic, plants, Neottia, Monotropa, &c., and in that of green plants like Erica, Fagus, and Pinus. It is, however, a well- known fact that ordinary green plants cannot utilize vegetable débris directly, and forest trees do so in appearance only, for the fungi, yeasts and bacteria there are actively decomposing the leaves and other remains. A class of pseudo-symbiotic organisms are, however, being brought into the foreground, where the combined action of two symbionts results in the death of or injury to a third plant, each symbiont alone proving harmless. Some time ago Vuillemin showed that a disease in olives results from the invasion of a bacillus (B. oleæ), which can, however, only obtain its way into the tissues through the passages driven by the hyphæ of a fungus (Chætophoma). The resulting injury is a sort of burr. This observer also observed the same bacillus and fungus in the canker burrs of the ash.
58.
Among many similarcases well worth further attention are the invasion of potato-tubers by bacteria, these making their way down the decaying hyphæ of pioneer fungi. Professor Marshall Ward has seen tomatoes infected by similar means, and other facts show that many bacteria which quicken the rotting of wood are thus led into the tissues by fungi. Probably no subject in the whole domain of cryptogamic botany has wider bearings on agricultural science than the study of the flora and changes on and in manure and soil. Nitrifying bacteria play a very important part by providing plant life with a most necessary food. They occur in the soil, and two kinds have been described—the one kind converting ammonia into nitrous acid, and the other changing nitrous into nitric acid. We are principally indebted to Winogradsky for our knowledge of these bacteria; he furnishes instances of the bearing of bacteriological work on this department of science, and explains, not only the origin of nitre-beds and deposits, but also the way the ammonia compounds fixed by the soil in the neighbourhood of the root-hairs are nitrified, and so rendered directly available to plant life. The investigations of other observers show that the nitrifying organism is a much more highly-developed and complex form than had been suspected; that it can be grown on various media, and that it exhibits considerable polymorphism—i.e., it can be made to branch out and show other characteristics of a true fungus. “I have,” writes Professor Ward, “for some time insisted on the fact that river water contains reduced forms of bacteria—i.e., forms so altered by exposure to light, changes of temperature, and the low nutritive value of the water, that it is only after prolonged culture in richer food media that their true nature becomes apparent.” Strutzer and Hartleb show that the morphological form of the nitrifying organism can be profoundly altered by just such variations of the conditions described by Ward, and that it occurs as a branched mycelial form; as bacilli or bacteria; or as cocci of various dimensions, according to the conditions.
59.
“These observations, andothers made on variations in form (polymorphism) in other fungi and bacteria, open out a vast field for further work, and must lead to advancement in our knowledge of these puzzling organisms; they also help us to explain many inconsistencies in the existing systems of classification of the so- called ‘species’ of bacteria as determined by test-tube culture.” Algæ.—The algals have a special charm for microscopists. I am free to confess my interest in these organisms, and for several reasons. In this humid climate of ours they are accessible during the greater part of the year; they can be found in any damp soil, in bog, moss, and in water—indeed, wherever the conditions for their existence seem to be at all favourable for development. Should the soil dry up for a time, when the rain returns algæ are seen to spring into life and give forth their dormant spores, which once more resume the circle of formation and propagation. In the earliest stage of development the spore or spore cell is so very small when in a desiccated state, that any number may be carried about by the slightest breath of air and borne away to a great distance. To all such organisms I originally gave the name of Ærozoa; now recognised as ærobic and anærobic organisms (Fig. 281). Fig. 281.—Ærobic Spores × 200. 1. Ærobic fungi caught over a sewer; 2. Fragments of Penicillium spores; 3. Ærobic fungi taken in the time of the cholera visitation, 1854.
60.
With reference tothe ærobic bacteria I have only to add that in addition to the simple mode of taking them on glass slides smeared over with glycerine, special forms of æroscopes are now in use for the purpose, consisting of a small cylinder in which a current of air is produced by an aspirator and diffused through a glass vessel containing a sterilised fluid. These are in constant use in all bacteriological laboratories. The results obtained are transferred to sterilised flasks or tubes as those shown in a former chapter. Miquel, who has given considerable attention to the subject of ærobic and anærobic bacteria, reckons that the number of spores that find their way into the human system by respiration, even should health be perfectly sound, may be estimated at 300,000 a day. One of the most commonly met with forms of micro-organisms is Leptothrix buccalis. It chiefly finds its nutritive material in the interstices of the teeth, and is composed of short rods and tufted stems of vigorous growth, to which the name of Bacillus subtilis has been given (Fig. 282). Among numerous other fungoid bodies discovered in the mouth, Sarcinæ have been found. See Plate IX., No. 7.
61.
Fig. 282.—Section ofthe Mucous Membrane of the Mouth, × 350. Showing: a. The denser connective tissue; b. Teased out tissue; c. Muscular fibre; d. Leptothrix buccalis, together with minute forms of bacteria and micrococci; e. Ascomycetes and starch granules. The Beggiatoa, a sewage fungus, found by me in the river Lea water of 1884 growing in great profusion, consists chiefly of mycelial threads and a number of globular, highly refractive bodies, and may be regarded as evidence of the presence in the water of an abnormal amount of sulphates which set free a gas, sulphuretted hydrogen, of a dangerous and offensive character. Another curious body closely allied to Beggiatoa alba is Cladothrix; this assumes a whitish pellicle on the surface of putrefying liquids. These saprophytes obtain nourishment from organic matter; nevertheless they are not true parasites in the first stage of their existence, during which they live freely in the water or in damp soil; they, however, become pathogenic parasites when they penetrate
62.
into the tissuesof animals, and necessarily live at the expense of their host. Fungi, Algæ, Lichens, etc. Tuffen West, del. Edmund Evans. Plate I. Bacteria, as I have said, were for a long time classed with fungi under the name of Schizomycetes. But the more recent researches into their organisation, and more especially into their mode of reproduction, show that they rather more resemble a group of algæ devoid of chlorophyll. Zopf asserts that the same species of algals may at one time be presented in the form of a plant living freely in
63.
water, or indamp ground, in association with chlorophyllaceous protoplasm, and at another in the form of a bacterium devoid of green colouring matter, and receiving nourishment from organic substances previously elaborated by plants or animals, thus accommodating itself, according to circumstances, to two very different modes of existence. That widely-distributed single-cell plant, the Palmoglœa macrococca of Kützing, that spreads itself as a green slime over damp stones, walls, and other bodies, affords an example. If a small portion be scraped off and placed on a slip of glass, and examined with a half or a quarter-inch power, it will be seen to consist of a number of ovoid cells, having a transparent structureless envelope, nearly filled by granular matter of a greenish colour. At certain periods this mass divides into two parts, and ultimately the cell becomes two. Sometimes the cells are united end to end, just as we see them united in the actively-growing yeast plant; but in this case the growth is accelerated, apparently, by cold and damp. Another plant belonging to the same species, the Protococcus pluvialis, is found in every pool of water, the spores of which must be always floating in the air, since they appear after every shower of rain. Protococcus pluvialis is furnished with motile organs—two or more vibratile flagella passing through perforations in the cell-wall— whereby, at certain stages, they move rapidly about. The flagella are distinctly seen on the application of the smallest drop of iodine. The more remarkable of the several forms presented by the plant is that of naked spores, termed by Flotow Hæmatococcus porphyrocephalus. These minute bodies are usually seen to consist of green, red, and colourless granules in equal proportions, and occupying different portions of the cell. They seem to have some share in the after subdivision of the cell (Fig. 283). There are also still-cells, which sub-divide into two, while the motile cells divide into four or eight. It is not quite clear what becomes of the motile zoospores, B, but as they have been seen to become encysted, they
64.
doubtless have aspecial function, or become still-cells under certain circumstances. It appears that both longitudinal and transverse division of the primordial cell takes place; and that the vibratile flagella of the parent cell retain to the last their function and their motion after the primordial cell has become detached and transformed into an independent secondary cell (Fig. 283, G). Fig. 283.—Cell Development. (Protococcus pluvialis.) Protococcus pluvialis, Kützing. Hæmatococcus pluvialis, Flotow. Chlamidococcus versatilis, A. Braun. Chlamidococcus pluvialis, Flotow and Braun. A. Division of a simple cell into two, each primordial vesicle having developed a cellulose envelope; B. Zoospores, having escaped from a cell; C. Division of an encysted cell into segments; D. Division of another cell, with vibratile flagella projecting through cell-wall; E. An encysted flagellate cell; F. Division of an encysted nucleated cell into four parts, with vibratile filaments projecting; G. Fission of a young cell. The most striking of the vital phenomena presented by Protococcus is that of periodicity. Certain forms—for instance, encysted zoospores, of a certain colour, appear in a given infusion, at first
65.
exclusively, then theygradually diminish, become more and more rare, and finally disappear altogether. After some time their number again increases, and this may be repeated. Thus, a cell which at one time presented only still forms at another contained only motile ones. The same may be said with respect to segmentation. If a number of motile cells be transferred from a larger vessel into a smaller one, in the course of a few hours most of them will have subsided to the bottom, and in the course of the day observed to be on the point of sub-division. On the following morning division will have become completed; on the next day the bottom of the vessel will be found covered with a new generation of self-dividing cells, which, again, will produce another generation. This regularity, however, is not always observed. The influence of every change in the external conditions of life upon the plant is very remarkable. It is only necessary to pour water from a smaller into a larger or shallower vessel to at once induce segmentation of cells. The same phenomenon occurs in other algals; thus Vaucheria almost always develops zoospores at whatever time of year they may be brought from their natural habitat into a warm room. Light is conducive to the manifestation of vital action in the motile spores; they usually collect in great numbers on the surface of the water, and at that part exposed to the strongest light. But in the act of propagation, on the contrary, and when about to pass into the still condition, the motile Protococcus cell seems to shun light, and falls to the bottom of the vessel. Too strong sunlight, as when concentrated by a lens, quickly kills the young zoospores. A temperature of undue elevation is injurious to the development of their vital activity and the formation of the zoospores. Frost destroys motile, but not still zoospores.55 Stephanosphæra pluvialis is a conspicuous variety of the fresh-water algals, described by Cohn. It consists of a cell containing eight primordial cells filled with chlorophyll, uniformly arranged (see Plate I., No. 24 d). The globular mother-cell rotates, somewhat in the same way as the volvox, by vibratile flagella, two of which are seen
66.
projecting from eachcell and piercing the transparent outer cell wall. Every cell divides first into two, then four, and lastly eight cells, each one of which again divides into a number of micro-gonidia, which have a motion within the mother-cell, and ultimately escape from it. Under certain circumstances each of the eight young cells is observed to change places in the interior of the cell; eventually they escape, lose their flagella, form a thicker membrane as at b, and for a time remain motionless, and sink to the bottom of the vessel in which they are contained. If the vessel is permitted to become thoroughly dry, and then again has water poured into it, motile cells reappear; from which circumstance it is probable that these represent the resting spores of the plant. When in the condition of greatest activity its division into eight is perfected during the night, and early in the morning light the young cells escape and pass through similar changes. It is calculated that in eight days, under favourable circumstances, 16,777,216 families may be formed from one resting-cell of Stephanosphæra. In certain of the cells, and at particular periods, remarkable amœboid bodies (Plate I., No. 24 c) make their appearance. There is a marked difference between Stephanosphæra and Chlamydococcus, for while in the latter the individual portions of a primordial cell separate entirely from one another, each developing its own enveloping membrane, and ultimately escaping as a unicellular individual; in the former, on the other hand, the eight portions remain for a time living in companionship. Volvocineæ.—A fresh-water unicellular plant of singular beauty and interest to the microscopist is the Volvox globator (Plate I., No. 15). No. 16 represents a portion of another cell, with brownish amœboid bodies enclosed in the protoplasmic web. It is common to our fresh- water pools, and attains a diameter of about 1⁄20th or 1⁄30th of an inch. Its movement is peculiar, a continued roll onwards, or a rotation like that of a top; at other times it glides along smoothly. When examined under a sufficiently high power, it is seen to be a hollow sphere, studded with green spots, and traversed by green threads connecting each of the spots or spores with the maternal
67.
cell. From eachof the spores proceed two long flagella, lashing filaments, which keep the globular body on the move. After a time the sphere bursts, and the contained sporules issue forth and speedily pass through a similar stage of development. These interesting cells were long taken to be animal bodies. Ehrenberg described them as Monads, possessing a mouth, stomach, and an eye. The setting free of the young volvox is essentially a process of cell division, occurring during the warmer periods of the year, and, as Professor Cohn shows, is a considerable advance upon the simpler conjugation of two smaller cells in desmids; it more closely resembles that which prevails among the higher algæ and a large number of cryptogams. As autumn advances the volvox spherules usually cease to multiply by the formation of zoosporanges, and certain of their ordinary cells begin to undergo changes by which they are converted, some into male or sperm-cells, others into germ- cells, but the greater number appear to remain sterile. Both kinds of cells at first so nearly resemble each other that it is only when the sperm cells begin to undergo sub-division that they are seen to be about three times the size of the sterile cells. Then the primary cell resolves itself into a cluster of peculiar secondary cells, each consisting of an elongated body containing an orange-coloured endochrome and a pair of long flagella, as seen in the antherozoids of the higher cryptogams. As the sperm-cells approach maturity the clusters may be seen to move within them; the bundles then separate and show an independent active movement while still within the cavity of the primary cell, and finally escape through a rupture in the cell-wall, rapidly diffusing themselves as they pass through the cavity. The germ-cells continue to increase in size without undergoing sub-division, at first showing large vacuoles in their protoplasm, but subsequently becoming filled with a darker coloured endochrome. The form of the cell also changes from its flask-like shape to the globular, and at the same time seems to acquire a firmer envelope. Over this the swarming antherozoids diffuse themselves and penetrate the substance to the interior, and
68.
are then lostto view. The product of this fusion, Cohn tells us, is a reproductive cell, or “oospore,” which speedily becomes enveloped in another membrane with a thicker external coat, beset with conical- pointed processes; and now the chlorophyll of the young cell gives place, as in Palmoglæ, to starch and reddish or orange-coloured, and a more highly refractive, fluid. As many as forty of such oospores have been counted in a single sphere of volvox, which then acquires the peculiar appearance observed by Ehrenberg, and described by him under the name of Volvox stellatus. The further history of this wonderful spheroid unicellular plant has been traced out by Kirchner, who found that their germination commences in the early months of the year—in February—with the liberation of the spherical endospore from its envelope and its division into four cells. A remarkable phenomenon has been observed by Dr. Braxton Hicks —the conversion of an ordinary volvox cell into a moving mass of protoplasm that bears a striking resemblance to the well-known amœba. “Towards the end of the autumn the endochrome mass of the volvox increases to nearly double its ordinary size, but instead of undergoing the usual sub-division so as to produce a macrogonidium, it loses its colour and regularity of form, and becomes an irregular mass of colourless protoplasm, containing a number of brownish granules.” The final change and the ultimate destination of these curious amœboid bodies have not been satisfactorily made out, but from other observations on the protoplasmic contents of the cells of the roots of mosses, which in the course of two hours become changed into ciliated bodies, it is believed that this is the mode in which these fragile structures are enabled to retain life and to resist all the external conditions, such as damp, dryness, and the alternations of heat and cold. It would be quite impossible to deny the great similarity there is between the structure of volvox and that of the motile cell of Protococcus pluvialis. The influence of reagents will sometimes cause the connecting processes of the young cells, as in Protococcus, to be drawn back into the central mass, and the connecting threads are sometimes seen as double lines, or tubular
69.
prolongations of themembrane. At other times they appear to be connected by star-like prolongations to the parent cell (Plate I., No. 15), presenting an almost identical appearance with Pediastrum pertusum. Another body designated by Ehrenberg Sphærosira volvox is an ordinary volvox in a different stage of development; its only features of dissimilarity being that a large proportion of the green cells, instead of being single, are double or quadruple, and that the groups of flagellate cells form by their aggregation discoid bodies, each furnished with a single flagellum. These clusters separate themselves from the parent cell, and swim off freely under the forms which have been designated Uvella and Syncrypta by Ehrenberg. Mr. Henry Carter, F.R.S., who made a careful investigation of unicellular plants, described Sphærosira as the male, or spermatic form of volvox. Among other organisms closely allied to volvox and included in Volvocineæ, affording the microscopist many interesting transitional forms in their various modes of fructification, are the Eudorina, still- water organisms that pass through a similar process of reproduction as the volvox. In the Pandorina morum, its reproduction is curiously intermediate between the lower and the higher types; as within each cell is a mulberry-like mass, composed of cells possessing a definite number of swarm spores, sixteen usually, which rupture the mother cell, and swim off furnished with a pair of flagella. A similar process takes place in some of the Confervaceæ and other fresh-water algæ. The Palmella, again, consist of (Plate I., No. 21) minute organisms of very simple structure, which grow either on damp surfaces or in fresh water. The stonework of some of our churches is often seen to be covered with a species of Palmella, that take the form of an indefinite slimy film. The “red snow” of Arctic or Alpine regions, considered to be a species of Protococcus, is frequently placed among Palmella. A more characteristic form of the P. cruenta is the Hæmatococcus sanguinis, the whole mass of which is sub-divided by partitions enclosing a larger or smaller number of cells, which diffuse their granular contents through the gelatinous mass in which their several changes take place. The albuminoid envelope of these
70.
masses is seento contain parasitic growths, which have given rise to some discussion, especially when their filaments are observed to radiate in various directions. The Oscillariaceæ constitute a genus of Confervaceæ which have always had very great interest for the microscopist in consequence of their very remarkable animal-like movements, and from which they derive their generic name. For more than a century these Bacillaria have excited the curiosity of all observers without any one having derived more than an approximate idea of their remarkable rhythmical movements. The frustule consists of a number of very fine short threads attached together by a gelatinous sheath, in one species all of equal length. Their backward and forward movement is of a most singular character; the only other conferva in which I have seen a motion of a similar kind is the Schizonema. In this species the frustules are packed together in regular series, the front and side views being always in the same direction. These several bodies move along within the filamentous sheath without leaving their respective places. On carefully following the movement, it is seen at first much extended, and then more compressed, while the frustules become more linear in their arrangement, and present a closer resemblance to Bacillaria paradoxa, augmented by the circumstance that the frustules are seen to move in both directions. A frustule of Schizonema can move independently of the sheath, and so will a detached frustule of bacillaria. This peculiar and exceptionally anomalous phenomenon as that of the movements of bacillaria can hardly be confined to a solitary species. The movements of the frustules are much accelerated by warmth and light. The longer filaments of other minute species only slightly exhibit any motion of the kind, but have peculiar undulating motions. Confervaceæ are a genus of algals. The species consist of unbranched filaments composed of cylindrical or moniliform cells, with starch granules. Many are vesicular, and all multiply by zoospores generated in the interior of the plant at the expense of the granular matter. They are, for the most part, found in fresh
71.
Fig. 284.—Confervaceæ. 1. Volvoxglobator; 2. A section of volvox, showing the flagellate margin of the cell; 3. A portion more highly magnified, to show the young volvocina, with their nuclei and thread-like attachments; 4. Spirogyra, near which are spores in different stages of development; 5. Conferva floccosa; 6. Stigeoclonium protensum, jointed filaments and single zoospores; 7. Staurocarpus gracilis, conjugating filaments and spores. water attached or floating, some in salt water, and a few in both, in colour usually green, but occasionally olive, violet, and red. The Confervaceæ proper are often divided into four families: 1. Hydrodictidæ; 2. Zygnemidæ; 3. Confervidæ; 4. Chætophoridæ. To the microscopist all the plants of this genera are extremely interesting as subjects for the study of cell multiplication. The process usually takes place in the terminal cell, the first step in which is the division of the endochrome, and then follows a sort of hour-glass contraction across the cavity of the parent cell, whereby it is divided into two equal parts. This is better seen in some of the desmids than in Fig. 284, Nos. 4, 5, and 6. Some species are characterised by a different mode of reproduction; these possess a number of nuclei, and multiply by zoospores of two kinds, the largest of which have either two or four cilia, which germinate directly the smaller are biciliated; conjugation has been seen to take place in a few instances. Allied to the Confervaceæ is an interesting plant, Sphæroplea annulina, which has received careful attention from Cohn. The oospores of this plant are the product of a process partaking of a
72.
sexual nature, andwhen mature are filled with reddish fat vesicles which divide by segmentation. The Ædogoniaceæ also closely resemble Confervaceæ in habits of life, but differ in some particulars, especially so in the mode of reproduction (only a single large zoospore being set free from each cell) and by the almost complete fission of the cell-wall or one of the rings which serve as a hinge. The zoospores are the largest known among algals, and each is described as having a red eye-spot. The Chætophoraceæ form an interesting group of confervoid plants, and are usually found in running streams, as they prefer pure water. One of the characteristics of the group is that the extremities of the branches are prolonged into an acute-shaped termination, as represented in Fig. 284, No. 6. A very pretty object under the microscope is Draparnaldia glomerata, belonging to this species. It consists of an axis composed of a row of cells, and at regular intervals whorls of slender prolongations, containing chlorophyll or endochrome of a deeper green; these attain to an extraordinary length. The Batrachospermæ bear a strong resemblance to frog-spawn, from which they derive their name, and are chiefly a marine group of algals allied to the Rhodespermeæ or red seaweeds. The late Dr. A. Hassall first described them; they have since received more careful attention from M. Sirodot. They are reddish-green, extremely flexible, and nothing can surpass the grace of their movements in water; but when removed from their element they lose all form, and resemble a jelly-like substance without a trace of organisation; but if allowed to remain quiet they regain their original shape. The presence of the cell-membrane will be best demonstrated by breaking up the filaments, either by moving the thin glass cover, or by cutting through a mass of them in all directions with a fine dissecting knife. On now examining the slide, in most instances many detached empty pieces of the cell-membrane, with its striæ, will be seen, as well as filaments partly deprived of protoplasm. On
73.
Fig. 285.—Mesoglia vermicularis. theapplication of iodine all these appearances become more distinguishable in consequence of the filament turning red or brown, while the empty cells remain either unaffected, or present a slight yellowish tint, as is frequently the case with cellulose when old. With regard to the contents of the cell, the endochrome is coloured in the Oscillatoriæ, and is distinguishable by circular bands or rings around the axis of the cylindrical filament. Iodine stains them brown or red, and syrup and dilute sulphuric acid produce a beautiful rose colour. As to their mode of propagation, nothing positive is known. If kept for some time they gradually lose their green colour; a portion of the mass, becoming brown, sinks to the bottom of the vessel, and presents a granular layer. Mesoglia vermicularis (Fig. 285) consists of strings of cells cohering and held together by their membranous covering. In the lowly organised plant Vaucheria (Plate I., No. 23, V. sessilis)—so named after its discoverer Vaucher, a German botanist— a genus of Siphonaceæ, we have an example of true processes of sexual generation. The branching filaments are often seen to bear at their sides peculiar globular bodies or oval protuberances, nipple- shaped buddings-out of the cell-wall, filled with a dark-coloured endochrome and distributed in pairs, one of which curves round to meet the other, when conjugation is seen to take place. Near these bodies others are found with pointed projections, which have been described as “horns,” but these, Pringshelm says, are “antherids which produce antherozoids in their interior,” while the capsule-like bodies constituting the oospores become, when fertilised, a new
74.
generation, which swarmout through a cavity or aperture in the parent cell-wall. The fruit of fresh-water and most olive-green algals is enclosed in spherical cavities under the epidermis of the frond, termed conceptacles, and may be either male or female. The zoids are bottle-shaped and have flagella; the transparent vesicle in which they are contained is itself enclosed in a second of similar form. In monœcious and diœcious algals the female conceptacles are distinguished from the male by their olive colour. The spores, when developed, are borne on a pedicle emanating from the inner wall of the conceptacle. They rupture the outer wall at its apex; at first the spore appears simple, but soon after a series of changes takes place, consisting in a splitting up of the endochrome into six or eight masses of spheroidal bodies. A budding-out occurs in a few hours’ time, and ultimately elongates into a cylindrical thread. The Vaucheria present a double mode of reproduction, and their fronds consist of branching tubes resembling in their general character that of the Bryophyta, from which indeed they differ only in respect of the arrangement of their green contents. In that most remarkable plant Saprolegnia ferox, which is structurally so closely allied to Vaucheria, though separated from them by the absence of green colouring matter, a corresponding analogy in the processes of development takes place. In the formation of its zoospores, an intermediate step is presented between that of the algæ and a class of plants formally placed among fungi. The Ulvaceæ.—The typical form of seaweeds is the Ulva lactuca, well known from its fronds of dark-green “laver” on every coast throughout the world. Ulvæ are seen to differ but little from the preceding group of fresh-water algals. The specific difference is that the cells, when multiplied by binary subdivision, not only remain in firm connection with each other but possess a more regular arrangement. The frond plane of the algal is either more simple or lobed, and is formed of a double layer of cells closely packed together and producing zoospores. The whole group is chiefly
75.
distinguished from Porphyraby their green colour, the latter being roseate or purple. Ulvæ are mostly marine, with one or two exceptions. One species (U. thermalis) grows in the hot springs of Gastein, in a temperature of about 117° Fahr. The development of Ulvæ is seen in Fig. 286. The isolated cells, A, resemble in some points those of the Protococcus; these give rise to successive subdivisions determining the clusters seen at B and C, and by their aggregation to the confervoid filament shown at D. These filaments increase in length and breadth by successive additions, and finally take the form of fronds, or rows of cells. Fig. 286.—Successive Stages of Development of Ulvæ. A. Isolated spores; B and C. Clusters of cells; D. Cells in the filamentous stage. Fig. 287.—Sphacelaria cirrhosa, with spores borne at the sides of the branchlets. The marine greenish-olive algæ present a general appearance which might at first sight be mistaken for plants of a higher order of cryptogams. Their fronds have no longer the form of a filament, but assume that of a membranous expansion of cells. The cells in which zoospores are found have an increased quantity of coloured
76.
protoplasm accumulated towardsone point of the cell-wall; while the zoospores are observed to converge with their apices towards the same point. In some algæ, which seem to be closely related in form and structure to the Bryophyta, we notice this important difference, that the zoospores are developed in an organ specially destined for the purpose, presenting peculiarities of form and distinguishing it from other parts of the branching tubular frond. In the genus Derbesia distinct spore cases develop, a young branch of which, when destined to become a spore case, instead of elongating indefinitely, begins, after having arrived at a certain length, to swell out into an ovoid vesicle, in the cavity of which a considerable accumulation of protoplasm takes place. This is separated from the rest of the plant, and becomes an opaque mass, surrounded by a distinct membrane. After a time a division of the mass takes place, and a number of pyriform zoospores, each of which is furnished with flagella, are set free. Desmidiaceæ, Diatomaceæ, Algæ.
77.
Tuffen West, del.Edmund Evans. Plate II. In Cutleria (Fig. 288) we have a special feature of interest with two kinds of organs, seemingly opposed to each other with regard to their reproductive functions. The sporangia not only differ from those of other species, but the frond consists of olive-coloured irregularly-divided flagella, on each side of which tufts (sori) consisting of the reproductive organs, intermixed with hair-like bodies, are scattered. The zoospores are divided by transverse partitions into four cavities, each of which is again bisected by a longitudinal median septum. When first thrown off they are in appearance so much like the spores of Puccinia that they may be
78.
Fig. 288.—Cutleria dichotoma.Section of lacinia of a frond, showing the stalked eight- chambered oosporanges growing on tufts with intercalated filaments. Magnified 50 diameters. mistaken for them, although so very much larger than those of other olive-coloured algæ. Florideæ, the red algæ (Plate II.), present many varieties of structure, although less appears to be known of their reproductive processes than of lower forms of cryptogamic plants. These are, however, of three kinds. The first, to which the term polyspore has been applied, is that of a gelatinous or membranous pericarp or conceptacle, in which an indefinite number of zoospores are contained. This organ may be either at the summit or base of a branch, or it may be concealed in or below the cortical layer of the stem. In some cases a number of spore-bearing filaments emanate from a kind of membrane at the base of a spheroidal cellular perisporangium, by the rupture of which the zoospores formed from the endochrome of the filaments make their escape. Other changes have been observed; however, they all agree in one particular, namely, that the zoospore is developed in the interior of a cell, the wall of which forms its perispore, and the internal protoplasmic membrane endochrome, the zoospore itself, for the escape of which the perispore opens out at its apex. The second form is more simple, and consists of a globular or ovoid cell, containing a central granular mass; this ultimately divides into
79.
Fig. 289.—Dasya kutzingiana,with seed vessel and two rows of tetraspores. Magnified 50 diameters. four quadrate-shaped spores; these, on attaining maturity, escape by rupture of the cell-wall. Another organ, called a tetraspore, takes its origin in the cortical layer. The tetraspores are arranged either in an isolated manner along the branches, or in numbers together; in some instances the branches that contain them are so modified in form they look like special organs, and have been called stichidia; as, for example, in Dasya (Fig. 289). Of the third kind of reproductive organ a difference of opinion exists as to the signification of their antheridia; although always produced in precisely the same situations as the tetraspores and polyspores, they are agglomerations of little colourless cells, either united in a bunch, as in Griffithsia, or enclosed in a transparent cylinder, as in Polysiphonia, or covering a kind of expanded disc of peculiar form, as in Laurencia. According to competent observers, the cells contain spermatozoids. Nägeli describes the spermatozoid as a spiral fibre, which, as it escapes, lengthens itself in the form of a screw. Thuret, on the contrary, says the contents are granular, and offer no trace of a spiral filament, but are expelled from the cells by a slow motion. The antheridia appear in their most simple form in Callithamnion (Plate II., Nos. 32 and 34), being reduced to a small mass of cells composed by numerous little bunches which are sessile on the bifurcations of the terminal branches. The spores are simpler structures than the tetraspores, and mostly occupy a more important
80.
position. They arenot scattered through the frond, but grouped in definite masses, and generally enclosed in a special capsule or conceptacle, which may be mistaken for a tetraspore case. The simplest form of the spore fruit consists of spherical masses of spores attached to the wall of the frond, or imbedded in its substance, without a proper conceptacle; such a fruit is called a favellidium, and occurs in Halymenia; the same name is applied to the fruits of similar structures not perfectly immersed, as those of Gigartina, Gelidium, &c., where they form tubercular swellings on the lobes. In some, the tubercles present a pore at the summit, through which the spores emerge forth. In other cases, as in Ceramium (Plate II., Nos. 27 and 37), the spores occupy a more conspicuous place; a characteristic species is Delessaria (Plate II., No. 39), the coccidium either occurring on lateral branches, or is sessile on the face of the frond, when it consists of a case filled with angular- shaped spores attached to the wall of the case. The general external appearance of the red algæ is very varied, but it seems to attain to its deepest colouring in the Red Sea, which, it is said, is entirely due to the peculiarly vivid red seaweed. They are all exquisite objects for the microscope, as may be surmised from the few varieties presented in Plate II. The Florideæ of the warmer seas exhibit most elegantly formed fronds, as will be seen on reference to the “Phycologia Australica” of the late Dr. William Harvey, F.R.S. The Characeæ may be placed among the highest of the algals, if only for the complexity of their reproductive organs, which certainly offer a contrast in their simplicity of structure. Chara vulgaris, stonewort, is a simple fresh-water plant, preferring still freshwater ponds or slow-moving rivers running over a chalky soil. It thus derives the calcareous matter found in the axis of the plant, together with a small portion of silica. Its filaments (or branches, as some botanists prefer to call them) are given off in whorls. The Characeæ are a small family of acrogens, consisting of only two or three at most. They are monœcious and diœcious, the two kinds of fruit being often placed close together. They may easily be grown in a tall glass jar for observation. All that is necessary is to put the jar
81.
occasionally under thehouse tap and let the water run slowly over the top for a short time, thus renewing the contents without disturbing the plant. The hard water supplied to London suits chara better than softer water. Both chara and nitella are objects of great interest to microscopists, since in the former the important fact of vegetable circulation was first observed. A portion of the plant of the natural size is shown in Fig. 290, No. 1. Characeæ. Fig. 290.—Diagrammatic sketch of Chara. 1. A stem of Chara vulgaris, natural size; 2. Magnified view (arrows indicating the course taken by the chlorophyll); 3. A limb, with buds
82.
protruding; 4. Portionof a leaf of Vallisneria spiralis, showing cyclosis of chlorophyll granules. Each plant is composed of an assemblage of long tubiform cells placed end to end, with fixed intervals, around which the branchlets are disposed with great regularity. In nitella the stem and branches are composed of simple cells, which sometimes attain to several inches in length. Each node, or zone, from which the branches spring, consists of a single plate, or layer, of small cells, which are a continuation of the cortical layer of the internode (Fig. 290, No. 3) as an outgrowth. Each cell is partially filled with chlorophyll granules, and it is these that are seen under the microscope taking the course shown by the arrows (Fig. 290, No. 2). The rate of movement of the granules is accelerated by moderate warmth and retarded by cold. It is in viewing the circulation in water plants that the warm stage of the microscope is brought into use. Borne along with the protoplasmic stream are a number of solid particles consisting of starch granules and other matters. The method of viewing the circulation is by cutting sections off a portion of the plant with a very sharp knife, and arranging them in a growing cell with a few drops of water, and covering over with a thin cover-glass.
83.
Welcome to OurBookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com