docs: initial version of the documentation

This commit is contained in:
Misko Hevery 2014-12-08 14:29:04 -08:00
parent d2c7c84e8e
commit 829c28f3ee
16 changed files with 1307 additions and 0 deletions

View File

@ -0,0 +1,8 @@
# Change Detection
* Mechanisms by which changes are detected in the model
* DAG
* Order of evaluation
* Pure Functions
* `onChange` method
* Parser

View File

@ -0,0 +1,7 @@
# Expressions
## Binding Semantics
### Formatters
## Statement Semantics

View File

@ -0,0 +1,3 @@
# Record
## RecordRange

View File

@ -0,0 +1,3 @@
# Overview
* High level description of all of the components.

View File

@ -0,0 +1,590 @@
# Templates
Templates are markup which is added to HTML to declarativly describe how the application model should be
projected to DOM as well as which DOM events should invoke which methods on the controller. Templates contain
syntax which is core to Angular and allows for data-binding, event-binding, template-instantiation.
The design of template syntax has these properties:
* All data-binding expressions are easily identifiable. (i.e. there is never an ambiguity wether the value should be
interpreted as string literal or as an expression.)
* All events and their statments are easily identifiable.
* All places of DOM instantiation are easily identifiable.
* All places of variable declaration is esily identifiable.
The above properties guarantee that the templates are easy to parse by tools (such as IDEs) and reason about by people.
At no point is it necessary to understand which directives are active and what are their symantics in order to reason
about the template runtime characteristics.
## Summary
Below is a summary of the kinds of syntaxes which Angular templating supports. The syntaxes are explained in more
detail in fallowing sections.
<table>
<thead>
<tr>
<th>Description</th><th>Short</th><th>Canonical</th>
</tr>
<thead>
<tbody>
<tr>
<th>Text Interpolation</th>
<td>
`<div>{{exp}}</div>`
Example:
```
<div>
Hello {{name}}!
<br>
Goodbye {{name}}!
</div>
```
</td>
<td>
`<div [text|index]=exp>`
Example:
```
<div
[text|0]=" 'Hello' + stringify(name) + '!' "
[text|2]=" 'Goodbye' + stringify(name) + '!' ">
_<b>x</b>_
</div>
```
</td>
</tr>
<tr>
<th>Property Interpolation</th>
<td>
`<div name="{{exp}}">`
Example:
`<div class="{{selected}}">`
</td>
<td>
`<div [name]="stringify(exp)">`
Example:
`<div [class]="stringify(selected)">`
</td>
</tr>
<tr>
<th>Property binding</th>
<td>
`<div [prop]="exp">`
Example:
`<div [hidden]="true">`
</td>
<td>
`<div bind-prop="exp">`
Example:
`<div bind-hidden="true">`
</td>
</tr>
<tr>
<th>Event binding (non-bubbling)</th>
<td>
`<div (event)="statement">`
Example:
`<div (click)="doX()">`
</td>
<td>
`<div on-event="statement">`
Example:
`<div on-click="doX()">`
</td>
</tr>
<tr>
<th>Event binding (bubbling)</th>
<td>
`<div (^event)="statement">`
Example:
`<div (^mouseover)="hlite()">`
</td>
<td>
`<div on-bubble-event="statement">`
Example:
`<div on-bubble-mouseover="hlite()">`
</td>
</tr>
<tr>
<th>Declare reference</th>
<td>
`<div #symbol>`
Example:
```
<video #player>
<button (click)="player.play()">play</button>
```
</td>
<td>
`<div def="symbol">`
Example:
```
<video def="player">
<button on-click="player.play()">play</button>
```
</td>
</tr>
<tr>
<th>Inline Template</th>
<td>
`<div template="...">...</div>`
Example:
```
<ul>
<li template="ng-repeat: #item in items">
{{item}}
</li>
</ul>
```
</td>
<td>
`<template>...</template>`
Example:
```
<ul>
<template def-ng-repeat:"item"
bind-ng-repeat-in="items">
<li>
{{item}}
</li>
</template>
</ul>
```
</td>
</tr>
<tr>
<th>Explicit Template</th>
<td>
`<template>...</template>`
Example:
```
<template #ng-repeat="item"
[ng-repeat-in]="items">
_some_content_to_repeat_
</template>
```
</td>
<td>
`<template>...</template>`
Example:
```
<template def-ng-repeat="item"
bind-ng-repeat-in="items">
_some_content_to_repeat_
</template>
```
</td>
</tr>
</tbody>
</table>
## Property Binding
Binding application model data to the UI, is the most common kinds of bindings in an Angular application. The bindings
are always in the form of `property-name` which is assigned an `expression`. The generic form is:
<table>
<tr>
<th>Short form</th>
<td>`<some-element [some-property]="expression">`</td>
</tr>
<tr>
<th>Canonical form</th>
<td>`<some-element bind-some-property="expression">`</td>
</tr>
</table>
Where:
* `some-element` can be any existing DOM element.
* `some-property` (escaped with `[]` or `bind-`) is the name of the property on `some-element`. In this case the
dash-case is converted into camel-case `someProperty`.
* `expression` is a valid expression (as defined in section below).
Example:
```
<div [title]="user.firstName">
```
In the above example the `title` property of the `div` element will be updated whenever the `user.firstName` changes
its value.
Key points:
* The binding is to the element property not the element attribute.
* To prevent custom element from accidentaly reading the literal `expression` on the title element, the attribute name
is escaped. In our case the `title` is escaped to `[title]` through the addition of squre brackets `[]`.
* A binding value (in this case `user.firstName` will always be an expression, never a string literal)
NOTE: Unlike Angular v1, Angular v2 binds to properties of elements rather than attributes of elements. This is
done to better support custom elements, and allow binding for values other than strings.
NOTE: Some editors/server side pre-processors may have trouble generating `[]` arround the attribute name. For this
reason Angular also supports a canonical version which is prefixed using `bind-`.
### String Interpolation
Property bindings are the only data bindings which angular supports, but for convenience Angular supports interpolation
syntax which is just a short hand for the data binding syntax.
```
<span>Hello {{name}}!</span>
```
is a short hand for:
```
<span [text|0]=" 'Hello ' + stringify(name) + '!' ">_</span>
```
The above says to bind `'Hello ' + stringify(name) + '!'` expression to the zero-th child of the `span`'s `text`
property. The index is necessary in case there are more than one text nodes, or if the text node we wish to bind to
is not the first one.
Similarly the same rules apply to interpolation inside attributes.
```
<span title="Hello {{name}}!"></span>
```
is a short hand for:
```
<span [title]=" 'Hello ' + stringify(name) + '!' "></span>
```
NOTE: `stringify()` is a built in implicit function which converts its argument to a string representation, while
keeping `null` and `undefined` as empty strings.
## Local Varibles
## Inline Templates
Data binding allows updating the DOM's properties, but it does not allow for changing of the DOM structure. To change
DOM structure we need the ability to define child templates, and than instantiat these templates into Views. The
Views can than be inserted and removed as needed to change the DOM structure.
<table>
<tr>
<th>Short form</th>
<td>
```
parent template
<element>
<some-element template="instantiating-directive-microsyntax">child template</some-element>
</element>
```
</td>
</tr>
<tr>
<th>Canonical form</th>
<td>
```
parent template
<element>
<template instantiating-directive-bindings>
<some-element>child template</some-element>
</template>
</element>
```
</td>
</tr>
</table>
Where:
* `template` defines a child template and designates the anchor where Views (instances of the template) will be
inserted. The template can be defined implicitly with `template` attribute, which turns the current element into
a template, or explicitly with `<template>` element. Explicit declaration is longer, but it allows for having
templates which have more than one root DOM node.
* `instantiating-directive` is required for templates. The instantiating directive is responsible for deciding when
and in which order should child views be inserted into this location. An instantiating directive usually has one or
more bindings and can be represnted as either `instantiating-directive-bindings` or
`instantiating-directive-microsyntax` on `template` element or attribute. See template microsyntax for more details.
Example of conditionally included template:
```
Hello {{user}}!
<div template="ng-if: isAdimnistrator">
...administrator menu here...
</div>
```
In the above example the `ng-if` instantiator determins if the child view (an instance of the child template) should be
inserted into ther root view. The `ng-if` makes this decision based on if the `isAdimnistrator` binding is true.
The above example is in the shart form, for better clarity let's rewrite it in the canonical form, which is functionaly
identical.
```
Hello {{user}}!
<template [ng-if]="isAdimnistrator">
<div>
...administrator menu here...
</div>
</template>
```
NOTE: Only Instantiator directives can be placed on the template element. (Decorators, and Components are not allowed.)
### Template Microsyntax
Often times it is necessary to encode a lot of different bindings into a template to controll how the instantiation
of the templates occures. One such example is ng-repeat.
```
<form #foo=form>
</form>
<ul>
<template ng-repeat #person [in]="people" #i="index">
<li>{{i}}. {{item}}<li>
</template>
</ul>
```
Where:
* `ng-repeat` triggers the ng-repeat directive.
* `[in]="people"` binds to an iterable object to the `ng-repeat` controller.
* `#person` exports the implicit `ng-repeat` item.
* `#i=index` exports item index as `i`.
The above example is explicit but quite wordy, for this reason in most situatios a short hand version of the
syntax is prefferable.
```
<ul>
<li template="ng-repeat; #person; in=people; #i=index;">{{i}}. {{item}}<li>
</ul>
```
Notice how each key value pair is translated to `key=value;` statement in the `template` attribute. This makes the
repeat syntax a much shorter, but we can do better. Turns out that most punctuation is opional in the short version
which allows us to further shorten the text.
```
<ul>
<li template="ng-repeat #person in people #i=index">{{i}}. {{item}}<li>
</ul>
```
We can also optionaly use `var` instead of `#` and add `:` to `ng-repeat` which creates the fallowing recomended
microsyntax for `ng-repeat`.
```
<ul>
<li template="ng-repeat: var person in people; var i=index">{{i}}. {{item}}<li>
</ul>
```
The format is intentionally defined freely, so that developers of directives can build expressive microsyntax for
their directives. Fallowing describes a more formal definition.
```
expression: ... // as defined in Expressions section
local: [a-zA-Z][a-zA-Z0-9]* // exported variable name available for binding
internal: [a-zA-Z][a-zA-Z0-9]* // internal variable name which the directive exports.
key: [a-z][-|_|a-z0-9]]* // key which maps to attribute name
keyExpression: key[:|=]?expression // binding which maps an expression to a property
varExport: [#|var]local(=internal)? // binding which exports a local variable from a directive
microsyntax: ([[key|keyExpression|varExport][;|,]?)*
```
Where
* `expression` is an angular expression as defined in section: Expressions
* `local` is a local identifiar for local variables.
* `internal` is an internal variable which the directive exports for binding.
* `key` is an attribute name usually only used to trigger a specific directive.
* `keyExpression` is an property name to which the epression will be bound to.
* `varExport` allows exporting of directive internal state as varibles for further binding. If no `internal` name
is specified than the exporting is to an implicit variable.
* `microsyntax` allows you to build simple microsyntax which can still clearly identify which expressions bind to
which properties as well as which varibales are exported for binding.
NOTE: the `template` attribute must be present to make it clear to the user that a sub-template is being created. This
goes allong the philosophy that the developer should be able to reason about the template without understanding the
semantics of the instantiator directive.
## Binding Events
Binding events allows wiring events from DOM (or other components) to the Angular controller.
<table>
<tr>
<th>Short form</th>
<td>`<some-element (some-event)="statement">`</td>
</tr>
<tr>
<th>Canonical form</th>
<td>`<some-element on-some-event="statement">`</td>
</tr>
</table>
Where:
* `some-element` Any element which can generate DOM events (or has angular directive which generates the event).
* `some-event` (escaped with `()` or `bind-`) is the name of the event `some-event`. In this case the
dash-case is converted into camel-case `someEvent`.
* `statement` is a valid statement (as defined in section below).
By default angular anly listens to the element on the event, and ignores events which bubble. To listen to bubbled
events (as in the case of clicking on any child) use the bubble option (`(^event)` or `on-bubble-event`) as shown
bellow.
<table>
<tr>
<th>Short form</th>
<td>`<some-element (^some-event)="statement">`</td>
</tr>
<tr>
<th>Canonical form</th>
<td>`<some-element on-bubble-some-event="statement">`</td>
</tr>
</table>
Example:
```
@Component(...)
class Example {
submit() {
// do something when button is clicked
}
}
<button (click)="submit()">Submit</button>
```
In the above example, when clicking on the submit button angular will invoke the `submit` method on the surounding
component's controller.
NOTE: Unlike Angular v1, Angular v2 treats event bindings as core constructs not as directives. This means that there
is no need to create a event directive for each kind of event. This makes it possible for Angular v2 to easily
bind to custom events of Custom Elements, whos event names are not known ahead of time.
## Expressions, Statements and Formatters
Angular templates contain expressions for binding to data and statments for binding to events. Expressions and statments
have different semantics.
### Expressions
Expressions can be used to bind to a properties only. Expressions represent how data should be projected to the View.
Expressions should not have any sideeffects and should be idempotent. Examples of where expressions can be used in
Angular are:
```
<div title="{{expression}}">{{expression}}</div>
<div [title]="expression">...</div>
<div bind-title="expression">...</div>
<div template="ng-if: expression">...</div>
```
Expressions are simplified version of expression in the langugage in which you are writing your application. (i.e.
expressions fallow JS syntax and semantics in JS and Dart syntax and semantics in Dart). Unlike expressions in the
langugage, binding expressions behave differently in following ways:
* *Must be defined*: Anlike Angular v1, Angular v2 will throw an error on dereferencing fields which are not defined.
For example: `user.name` will throw an error if `user` is defined but it does not have `name` property. If the `name`
property is not known, it must be declared and set to some value such as empty string, `null` (or `undefined` in JS).
This is done to allow early detection of errors in the templates.
* *Safe dereference*: Expressions `user.name` where `user` is null will throw `NullPointerException` in the langugage.
In contrast Angular will silently ignore `null` on `user`. This is done because Views often have to wait for the data
to arrive from the backend and many fields will be null until the data arrives. Safe dereference so cammon in the
Views, that we have made it the default.
* *Single expression*: An expression must be a single statemnet. (i.e. no `;`)
* *No assignments*: Binding expressions can not contain assignments.
* *No keywords*: Binding expressions can not contain keywords such as: `var`, `if`, and so on.
* *Formatters*: Angular expressions can be piped through formatters to further transform the binding value.
(See: Formatters)
Examples of some expressions and their behavior:
Given:
```
class Greeter {
name:string;
}
```
* `name` : Will result in the value of the `name` property on the `Greeter` class.
* `name.length`: Will result in either the length of the `name` string or `undefined` (`null` in Dart) if `name`
property is `null` or `undefined`. Example of: safe dereference.
* `foo`: Will thrown on error because `foo` is not declared on the `Greeter` class. Example of: Must be defined
* `name=1`: Not allowed because fo assignment.
* `name; name.length`: Not allowed because of multiple statments.
### Statements
Statements can be used to bind to events only. Statements represent actions to trigger as a response to an event.
Examples of where statments can be used in Angular are:
```
<div (click)="statments">...</div>
<div on-click="statments">...</div>
```
Statements are similar to statments in the langugage in which you are writing your application. (i.e.
statments fallow JS syntax and semantics in JS and Dart syntax and semantics in Dart). Unlike statments in the
langugage, binding expressions behave differently in following ways:
* *Unsafe dereference*: Expressions `user.verify()` where `user` is null will throw `NullPointerException` in the
langugage as well as in statments. (In contrast to Safe dereference in Angular expressions.) While angular protects
you from null dereferencing in expressions due to lazy loading of data, no such protection is required for statments,
and doing so would make it harder to detect typos in statements.
* *Multiple statements OK*: Statements can be composed from more than one statemnet. (i.e. no `doA(); doB()`)
* *Assignments OK*: Event bindings can have sideeffects and hence assignments are allowed.
* *No keywords*: Statements can not contain keywords such as: `var`, `if`, and so on.
* *No Formatters*: Angular statements can not contain formatters. (Formatters are only usefull for data binding)
## Further Reading
* [Template Syntax Constraints and Reasoning](https://docs.google.com/document/d/1HHy_zPLGqJj0bHMiWPzPCxn1pO5GlOYwmv-qGgl4f_s)

View File

@ -0,0 +1,341 @@
# Directives
Directives are classes which get instantiated as a respones to a particular DOM strcture. By controlling the DOM stracture, what directives are imported, and their selectors, the developer can use the [composition pattern](http://en.wikipedia.org/wiki/Object_composition) to get desirable application behavior.
Directives are the cornerstone af Angular application. We use Directives to break complex problems into smaller more reusable components. Directives, allow the devolper turn HTML into a DSL and than controll the application assembly process.
Angular applications do not have a main method. Instead they have a root Component. Dependency Injection than assembles the directives into a working Angular application.
There are three different kinds of directives (described in mored detailed in later sections).
1. *Decorators*: can be placed on any DOM element and can be combined with other directives.
2. *Components*: Components have encapsulated view and can configure injectors.
3. *Instantiator*: Is responsible for adding or removing child views in parent view. (i.e. ng-repeat, ng-if)
## CSS Selectors
Decorators are instantiated whenever the decorator CSS selector matches the DOM structure.
Angular supports these CSS selector constructs:
* Element name: `name`
* Attribute: `[attribute]`
* Attribute has value: `[attribute=value]`
* Attribute contains value: `[attribute*=value]`
* Class: `.class`
* AND operation: `name[attribute]`
* OR operation: `name,.class`
Angular does not support these (and any CSS selector which crosses element boundries):
* Descendant: `body div`
* Direct descendant: `body > div`
* Adjascent: `div + table`
* Sibling: `div ~ table`
* Wildcard: `*`
* ID: `#id`
* Pseudo selectors: `:pseudo`
Given this DOM:
```<input type="text" required class="primary">```
These CSS selectors will match:
* `input`: Triggers whenever element name is `input`.
* `[required]`: Triggers whenever element contains a required attribute.
* `[type=text]`: Triggers whenever element contains attribute `type` whose value is `text`.
* `.primary`: Triggers whenever element class contains `primary`.
CSS Selectors can be combined:
* `input[type=text]`: Triggers on element name `input` which is of `type` `text`.
* `input[type=text], textarea`: triggers on element name `input` which is of `type` `text` or element name `textarea`
## Decorators
The simplest kind of directive is a decorator. Directives are usefull for encapsulating behavior.
* Multiple decorators can be placed on a single element.
* Decorators do not introduce new evaluation context.
* Decorators are registered througt the `@Decorator` meta-data annotation.
Here is a triavial example of tooltip decorator. The directive will log a tooltip into the console on every time mouse enters a region:
```
@Decorator({
selector: '[tooltip]', // CSS Selector which triggers the decorator
bind: { // List which properties need to be bound
tooltip: 'text' // - DOM element tooltip property should be
}, // mapped to the directive text property.
event: { // List which events need to be mapped.
mouseover: 'show' // - Invoke the show() method ever time
} // the mouseover event is fired.
})
class Form { // Directive controller class, instantiated
// when CSS matches.
text:string; // text property on the Decorator Controller.
show(event) { // Show method which implements the show action.
console.log(this.text);
}
}
```
Example of usage:
```<span tooltip="Tooltip text goes here.">Some text here.</span>```
The developer of an applacation can now freely use the `tooltip` attribute wherever the behavior is needed. The code above has tought the browser a new reusable and declarative bahavior.
Notice that databinding will work with this decorator with no further effort as show below.
```<span tooltip="Greetings {{user}}!">Some text here.</span>```
## Components
Component is a directive which uses shadow DOM to create encapsulate visual behavior. Components are tipically used to create UI widgets or to break up the application into smaller components.
* Only one component can be present per DOM element.
* Components CSS selectors usualy trigger on element names. (Best practice)
* Component has its own shadow view which is attached to the element as a Shadow DOM.
* Shadow view context is the component instance. (i.e. template expressions are evaluated against the component instance.)
>> TODO(misko): Configuring the injector
Example of a component:
```
@Component({ | Component annotation
selector: 'pane', | CSS selector on <pane> element
bind: { | List which property need to be bound
'title': 'title', | - title mapped to component title
'open': 'open' | - open mapped to component title
}, |
template: new TemplateConfig({ | Define template to be used with component
url: 'pane.html', | - URL of template HTML
cssUrl: 'pane.css' | - URL of CSS to be used with the component
}) |
}) |
class Pane { | Component controller class
title:string; | - title property
open:boolean;
constructor() {
this.title = '';
this.open = true;
}
// Public API
toggle() => this.open = !this.open;
open() => this.open = true;
close() => this.open = false;
}
```
`pane.html`:
```
<div class="outter">
<h1>{{title}}</h1>
<div class="inner" [hidden]="!visible">
<content></content>
</div>
</div>
```
`pane.css`:
```
.outter, .inner { border: 1px solid blue;}
.h1 {background-color: blue;}
```
Example of usage:
```
<pane #pane title="Example Title">
Some text to wrap.
</pane>
<button (click)="pane.toggle()">toggle</button>
```
## Instantiator
Instantiator is a directive which can controll instantiation of child views which are then inserted into the DOM. (Examples are `ng-if` and `ng-repeat`.)
* Instantiators can only be placed on `<template>` elements (or the short hand version which uses `<element template>` attribute.)
* Only one instantiator can be present per DOM template element.
* The instantiator is is created over the `template` element. This is known as the `ViewPort`.
* Instantiator can insert child views into the `ViewPort`. The child views show up as siblings of the `ViewPort` in the DOM.
>> TODO(misko): Relationship with Injection
>> TODO(misko): Instantiator can not be injected into child Views
```
@Instantiator({
selector: '[ng-if]',
bind: {
'ng-if': 'condition'
}
})
export class NgIf {
viewPort: ViewPort;
view: View;
constructor(viewPort: ViewPort) {
this.viewPort = viewPort;
this.view` = null;
}
set condition(value) {
if (value) {
if (this.view == null) {
this.view = this.viewPort.create();
}
} else {
if (this.view != null) {
this.viewPort.remove(this.view);
this.view = null;
}
}
}
}
```
## Dependency Injection
Dependency Injection (DI) is a key aspect of directives. DI allows directives to be assembled into different [compositional](http://en.wikipedia.org/wiki/Object_composition) hieranchies. Angular encourages [composition over inheritance](http://en.wikipedia.org/wiki/Composition_over_inheritance) in the application design (but inheritance based approaches are still supported).
When Angular directives are instantiated, the directive can ask for other related directives to be injected into it. By assembing the directives in different order and subtypes the application behavior can be controlled. A good mental model is that DOM structure controlles the directive instantiation graph.
Directive instantiation is triggered by the directive CSS selector matching the DOM structure. The directive in its constructor can ask for other directives or application services. When asking for directives the dependency is locating by fallowing the DOM hieranchy and if not found using the application level injector.
To better understand the kinds of injections which are supported in Angular we have broken them down into use case examples.
### Injecting Services
Service injection is the most straight forward kind of injection which Angular supports. It involves a component configureing the `componentServices` and than letting the directive ask for the configured service.
This example ilustrates how to inject `MyService` into `House` directive.
```
class MyService {} | Assume a service which needs to be injected
| into a directive.
|
@Component({ | Assume a top level application component which
selector: 'my-app', | configures the service, template and the
componentServices: [MyService], | directive into which we wish to inject the
template: new TemplateConfig({ | service.
url: 'my_app.html', |
directives: [House] |
}) |
}) |
class MyApp {} |
|
@Decorator({ | This is the directive into which we would like
selector: '[house]' | to inject the MyService.
}) |
class House { |
constructor(myService:MyService) { | Notice that in the constructor we can simply
} | ask for MyService.
} |
```
Assume fallowing DOM structure for `my_app.html`:
```
<div house> | The house attribute triggers the creation of House directive.
</div> | This is equivalent to:
| new House(injector.get(MyService));
```
### Injecting other Directives
Injecting other directives into directives fallows similar mechanism as injecting services, but with added constraint of visibility governed by DOM structure.
There are five kinds of visibilities:
* (no annotation): Inject a directives only if it is on the curent element.
* `@ancestor`: Inject a directive if it is at any element above the current element.
* `@parent`: Inject a directive which is direct parent of the current element.
* `@child`: Inject a list of direct children which match a given type. (Used with `Query`)
* `@descendant`: Inject a list of any children which match a given type. (Used with `Query`)
NOTE: if the injection constraint can not be satisfied by the current visibility constraint, than it is forward to normal injector which may provide a default value for the directive or it may throw an error.
Here is an example of the kinds of injections which can be achieved:
```
@Component({ |
selector: 'my-app', |
template: new TemplateConfig({ |
url: 'my_app.html', |
directives: [Form, FieldSet, |
Field, Primary] |
}) |
}) |
class MyApp {} |
|
@Decorator({ selector: 'form' }) |
class Form { |
constructor( |
@descendant sets:Query<FieldSet> |
) { |
} |
} |
|
@Decorator({ selector: 'fieldset' }) |
class FieldSet { |
constructor( |
@child sets:Query<Field> |
) { ... } |
} |
|
@Decorator({ selector: 'field' }) |
class Field { |
constructor( |
@ancestor field:Form, |
@parent field:FieldSet, |
) { ... } |
} |
|
@Decorator({ selector: '[primary]'}) |
class Primary { |
constructor(field:Field ) { ... } |
} |
```
Assume fallowing DOM structure for `my_app.html`:
```
<form> |
<div> |
<fieldset> |
<field primary></field> |
<field></field> |
</div> |
</fieldset> |
</form> |
```
### Shadow DOM effects on Dependency Injection
Shadow DOM provides encapsulation for components, so as a general rule it does not allow directive injections to cross the shadow DOM boundries.
## Further Reading
* [Composition](http://en.wikipedia.org/wiki/Object_composition)
* [Composition over Inheritance](http://en.wikipedia.org/wiki/Composition_over_inheritance)

View File

@ -0,0 +1,15 @@
# Formatters
Formatters can be appended on the end of the expressions to translated the value to a different format. Typically used
to controll the stringification of numbers, dates, and other data, but can also be used for ordering, maping, and
reducing arrays. Formatters can be chained.
NOTE: Formatters are known as filters in Angular v1.
Formatters syntax is:
```
```

View File

@ -0,0 +1,5 @@
# Components
* Different kinds of injections and visibility
* Shadow DOM usage
*

View File

View File

View File

@ -0,0 +1,21 @@
# HTML Template Compilation
* Process by which a HTML template is converted to a ProtoView
1. DOM parse()
2. Macro
3.
# HTML Template
* https://docs.google.com/document/d/1HHy_zPLGqJj0bHMiWPzPCxn1pO5GlOYwmv-qGgl4f_s
* https://docs.google.com/document/d/1kpuR512G1b0D8egl9245OHaG0cFh0ST0ekhD_g8sxtI
* https://docs.google.com/document/d/1DuFQKElIq293FlhQHvAp__NfP1XV9r8femZFMigm4-k
* Must understand without understanding directives
* IDE support
* local variables
# Binding Philosophy
# Binding to Shadow DOM

View File

@ -0,0 +1,209 @@
# View
## Overview
This document explains the concept of a View. View is a core primitive used by angular to render the DOM tree. ViewPort is location in a View which can accept child Views. Views for a tree structure which mimics the DOM tree.
* View is a core rendering construct. A running application is just a collection of Views which are nested in a tree like structure. The View tree is a simplified version of the DOM tree. A View can have a single DOM Element or large DOM structures. The key is that the DOM tree in the View can not undergo structural changes (only property changes).
* Views represent a running instance of a DOM Template. This implies that while elements in a View can change properties, they can not change structurally. (Structural changes such as, adding or removing elements requires adding or removing child Views into ViewPorts.)
* View can have zero or more ViewPorts. A ViewPort is a marker in the DOM which allows the insertion of child Views.
* Views are created from a ProtoView. A ProtoView is a compiled DOM Template which is efficient at creating Views.
* View contains a context object. The context represents the object instance against which all expressions are evaluated against.
* View contains a ChangeDetector for looking for detecting changes to the model.
* View contains ElementInjector for creating Directives.
## Simple View
Let's examine a simple View and all of its parts in detail.
Assume the following Component:
```
class Greeter {
greeting:string;
constructor() {
this.greeting = 'Hello';
}
}
```
And assume following HTML Template:
```
<div>
Your name:
<input var="name" type="Text">
<br>
{{greeting}} {{name.value}}!
</div>
```
The above template is compiled by the Compiler to create a ProtoView. The ProtoView is than used to create an instance of the View. The instantiation process involves cloning the above template and locating all of the elements which contain bindings and finally instantiating the Directives associated with the template. (See compilation for more details.)
```
<div> | viewA(greeter)
Your name: | viewA(greeter)
<input var="name" type="Text"> | viewA(greeter): local variable 'name'
<br> | viewA(greeter)
{{greeting}} {{name.value}}! | viewA(greeter): binding expression 'greeting' & 'name.value'
</div> | viewA(greeter)
```
The resulting View instance looks something like this (simplified pseudo code):
```
viewA = new View({
template: ...,
context: new Greeter(),
localVars: ['name'],
watchExp: ['greeting', 'name.value']
});
```
Note:
* View uses instance of `Greeter` as the evaluation context.
* View knows of local variables `name`.
* View knows which expressions need to be watched.
* View knows what needs to be updated if the watched expression changes.
* All DOM elements are owned by single instance of the view.
* The structure of the DOM can not change during runtime. To Allow structural changes to DOM we need to understand Composed View.
## Composed View
An important part of an application is to be able to change the DOM structure to render data for the user. In Angular this is done by inserting child views into the ViewPort.
Let's start with a Template such as:
```
<ul>
<li template="ng-repeat: person in people">{{person}}</li>
</ul>
```
During the compilation process the Compiler breaks the HTML template into these two ProtoViews:
```
<li>{{person}}</li> | protoViewB(Locals)
```
and
```
<ul> | protoViewA(SomeContexnt)
<template></template> | protoViewA(SomeContexnt): new ProtoViewPort(protoViewB)
</ul> | protoViewA(SomeContexnt)
```
The next step is to compose these two ProtoViews into actual view which is rendered to the user.
*Step 1:* Instantiate `viewA`
```
<ul> | viewA(SomeContexnt)
<template></template> | viewA(SomeContexnt): new NgRepeat(new ViewPort(protoViewB))
</ul> | viewA(SomeContexnt)
```
*Step2:* Instantiate `NgRepeat` directive which will receive the `ViewPort`. (The ViewPort has reference to `protoViewA`).
*Step3:* As the `NgRepeat` unrolls it asks the `ViewPort` to instantiate `protoViewB` and insert it after the `ViewPort` anchor. This is repeated for each `person` in `people`. Notice that
```
<ul> | viewA(someContext)
<template></template> | viewA(someContext): new NgRepeat(new ViewPort(protoViewB))
<li>{{person}}</li> | viewB0(locals0(someContext))
<li>{{person}}</li> | viewB1(locals0(someContext))
</ul> | viewA(lomeContexnt)
```
*Step4:* All of the bindings in the child Views are updated. Notice that in the case of `NgRepeat` the evaluation context for the `viewB0` and `viewB1` are `locals0` and `locals1` respectively. Locals allow the introduction of new local variables visible only within the scope of the View, and delegate any unknown references to the parent context.
```
<ul> | viewA
<template></template> | viewA: new NgRepeat(new ViewPort(protoViewB))
<li>Alice</li> | viewB0
<li>Bob</li> | viewB1
</ul> | viewA
```
Each View can have zero or more ViewPorts. By inserting and removing child Views to and from the ViewPort, the application can mutate the DOM structure to any desirable state. A View contain individual nodes or complex DOM structure. The insertion points for the child Views, known as ViewPorts, contain a DOM element which acts as an anchor. The anchor is either a `template` or a `script` element depending on your browser. It is used to identify where the child Views will be inserted.
## Component Views
A View can also contain Components. Components contain Shadow DOM for encapsulating their internal rendering state. Unlike ViewPorts which can contain zero or more Views, the Component always contain exactly one Shadow View.
```
<div> | viewA
<my-component> | viewA
#SHADOW_ROOT | (encapsulation boundary)
<div> | viewB
encapsulated rendering | viewB
</div> | viewB
</my-component> | viewA
</div> | viewA
```
## Evaluation Context
Each View as a context for evaluating its expressions. There are two kinds of contexts:
1. A component controller instance and
2. a Locals context for introducing Local variables into the View.
Let's assume following component:
```
class Greeter {
greeting:string;
constructor() {
this.greeting = 'Hello';
}
}
```
And assume following HTML Template:
```
<div> | viewA(greeter)
Your name: | viewA(greeter)
<input var="name" type="Text"> | viewA(greeter)
<br> | viewA(greeter)
{{greeting}} {{name.value}}! | viewA(greeter)
</div> | viewA(greeter)
```
The above UI is built using a single View, and hence single context `greeter`. It can be expressed in this pseudo-code.
```
var greeter = new Greeter();
```
The View contains two bindings:
1. `greeting`: This is bound to the `greeting` property on the `Greeter` instance.
2. `name.value`: This poses a problem. There is no `name` property on `Greeter` instance. To solve this we wrap the `Greeter` instance in the `Local` instance like so:
```
var greeter = new Locals(new Greeter(), {name: ref_to_input_element })
```
By wrapping the `Greeter` instance into the `Locals` we allow the view to introduce variables which are in addition to
the `Greeter` instance. During the resolution of the expressions we first check the locals, and then `Greeter` instance.
## View LifeCycle (Hydration and Dehydration)
Views transition through a particular set of states:
1. View is created from the ProtoView.
2. View can be attached to an existing ViewPort.
3. Upon attaching View to the ViewPort the View needs to be hydrated. The hydration process involves instantiating all of the Directives associated with the current View.
4. At this point the view is ready and renderable. Multiple changes can be delivered to the Directives from the ChangeDetection.
5. At some point the View can be removed. At this point all of the directives are destroyed during the dehydration precess and the view becomes inactive.
6. The View has to wait until it is detached from the DOM. The delay in detaching could be caused because an animation is animating the view away.
7. After the View is detached from the DOM it is ready to be reused. The view reuse allows the application to be faster in subsequent renderings.

View File

View File

@ -0,0 +1,105 @@
# Zones
A Zone is an execution context that persists across async tasks. You can think of it as thread-local storage for
JavaScript. Zones are used to intercept all async operation callbacks in the browser. By intercepting async
callbacks angular can automatically execute the change detection at the end of the VM turn to update the application
UI bindings. Zones means that in Angular v2 you don't have to remember to call `rootScope.$apply()` in your async call.
## Execution Context
```
zone['inTheZone'] = false;
zone.run(function () {
zone['inTheZone'] = true;
setTimeout(function () {
console.log('async in the zone: ' + zone['inTheZone']);
}, 0);
});
console.log('sync in the zone: ' + zone['inTheZone']);
```
The above will log:
```
sync in the zone: false
async in the zone: true
```
In the above example the `zone` is a global-callback-local variable. To the `zone` we can attach arbitrary properties
such as `inTheZone`. When we enter the zone, we get a new `zone` context (which inherits all properties from the
parent zone), once we leave the zone, the previous `zone` variable is restored. The key part is that when a async
callback is scheduled in the zone, as is the case with `setTimeout`, the current `zone` variable is captured and
restored on the callback. This is why the output of the `inTheZone` property inside the callback of the `setTimeout`
prints `true`.
## Callback Interception
In addition to storing properties on the current `zone`, zones can also allow us to intercept all async callbacks
and notify us before and after the callback executes.
```
zone.fork({
afterTask: function () {
// do some cleanup
}
}).run(function () {
// do stuff
});
```
The above example will execute the `afterTask` function not only after the `run` finishes, but also after any callback
execution which was registered in the `run` block.
## Putting it all together in Angular
In Angular2 it is not necessary to notify Angular of changes manually after async callback, because angular relevant
async callbacks are intercepted. The question is how do we know which callbacks are angular relevant?
```
/// Some other code running on page can do async operation
document.addEventListener('mousemove', function () {
console.log('Mouse moved.');
});
var AngularZone = {
afterTask: function () {
console.log('ANGULAR AUTO-DIGEST!');
}
};
var ngZone = zone.fork(AngularZone);
ngZone.run(function() {
console.log('I aware of angular, I should cause digest.');
document.addEventListener('click', function () {
console.log('Mouse clicked.');
});
});
```
Will produce:
```
I aware of angular, I should cause digest.
ANGULAR AUTO-DIGEST!
```
Moving the mouse will produce many:
```
Mouse moved.
```
But clicking will produce:
```
Mouse clicked.
ANGULAR AUTO-DIGEST!
```
Notice how the place where the listener was register will effect weather or not angular will be notified of the
async call and cause a change detection to run to update the UI.
Being able to globally intercept the async operation is important to have a seamless integration with all existing
libraries. But it is equally important to be able to differentiate between Angular and none Angular code running
on the same page concurrently.