docs: rewrite built-in directives section (#27273)

PR Close #27273
This commit is contained in:
Kapunahele Wong
2018-10-09 14:32:58 -04:00
committed by Andrew Kushnir
parent 7e3a60ad31
commit 2c2135d331
20 changed files with 924 additions and 231 deletions

View File

@ -0,0 +1,75 @@
button {
font-size: 100%;
margin: 0 2px;
}
div[ng-reflect-ng-switch], app-unknown-item {
margin: .5rem 0;
display: block;
}
#noTrackByCnt,
#withTrackByCnt {
color: darkred;
max-width: 450px;
margin: 4px;
}
img {
height: 100px;
}
.box {
border: 1px solid black;
padding: 6px;
max-width: 450px;
}
.child-div {
margin-left: 1em;
font-weight: normal;
}
.context {
margin-left: 1em;
}
.hidden {
display: none;
}
.parent-div {
margin-top: 1em;
font-weight: bold;
}
.course {
font-weight: bold;
font-size: x-large;
}
.helpful {
color: red;
}
.saveable {
color: limegreen;
}
.study,
.modified {
font-family: "Brush Script MT";
font-size: 2rem;
}
.toe {
margin-left: 1em;
font-style: italic;
}
.to-toc {
margin-top: 10px;
display: block;
}

View File

@ -0,0 +1,253 @@
<h1>Built-in Directives</h1>
<h2>Built-in attribute directives</h2>
<h3 id="ngModel">NgModel (two-way) Binding</h3>
<fieldset><h4>NgModel examples</h4>
<p>Current item name: {{currentItem.name}}</p>
<p>
<!-- #docregion without-NgModel -->
<label for="without">without NgModel:</label>
<input [value]="currentItem.name" (input)="currentItem.name=$event.target.value" id="without">
<!-- #enddocregion without-NgModel -->
</p>
<p>
<!-- #docregion NgModel-1 -->
<label for="example-ngModel">[(ngModel)]:</label>
<input [(ngModel)]="currentItem.name" id="example-ngModel">
<!-- #enddocregion NgModel-1 -->
</p>
<p>
<label for="example-bindon">bindon-ngModel: </label>
<input bindon-ngModel="currentItem.name" id="example-bindon">
</p>
<p>
<!-- #docregion NgModelChange -->
<label for="example-change">(ngModelChange)="...name=$event":</label>
<input [ngModel]="currentItem.name" (ngModelChange)="currentItem.name=$event" id="example-change">
<!-- #enddocregion NgModelChange -->
</p>
<p>
<label for="example-uppercase">(ngModelChange)="setUppercaseName($event)"
<!-- #docregion uppercase -->
<input [ngModel]="currentItem.name" (ngModelChange)="setUppercaseName($event)" id="example-uppercase">
<!-- #enddocregion uppercase -->
</label>
</p>
</fieldset>
<hr><h2 id="ngClass">NgClass Binding</h2>
<p>currentClasses is {{currentClasses | json}}</p>
<!-- #docregion NgClass-1 -->
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>
<!-- #enddocregion NgClass-1 -->
<ul>
<li>
<label for="saveable">saveable</label>
<input type="checkbox" [(ngModel)]="canSave" id="saveable">
</li>
<li>
<label for="modified">modified:</label>
<input type="checkbox" [value]="!isUnchanged" (change)="isUnchanged=!isUnchanged" id="modified"></li>
<li>
<label for="special">special: <input type="checkbox" [(ngModel)]="isSpecial" id="special"></label>
</li>
</ul>
<button (click)="setCurrentClasses()">Refresh currentClasses</button>
<div [ngClass]="currentClasses">
This div should be {{ canSave ? "": "not"}} saveable,
{{ isUnchanged ? "unchanged" : "modified" }} and
{{ isSpecial ? "": "not"}} special after clicking "Refresh".</div>
<br><br>
<!-- #docregion special-div -->
<!-- toggle the "special" class on/off with a property -->
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>
<!-- #enddocregion special-div -->
<div class="helpful study course">Helpful study course</div>
<div [ngClass]="{'helpful':false, 'study':true, 'course':true}">Study course</div>
<!-- NgStyle binding -->
<hr><h3>NgStyle Binding</h3>
<!-- #docregion without-ng-style -->
<div [style.font-size]="isSpecial ? 'x-large' : 'smaller'">
This div is x-large or smaller.
</div>
<!-- #enddocregion without-ng-style -->
<h4>[ngStyle] binding to currentStyles - CSS property names</h4>
<p>currentStyles is {{currentStyles | json}}</p>
<!-- #docregion NgStyle-2 -->
<div [ngStyle]="currentStyles">
This div is initially italic, normal weight, and extra large (24px).
</div>
<!-- #enddocregion NgStyle-2 -->
<br>
<label>italic: <input type="checkbox" [(ngModel)]="canSave"></label> |
<label>normal: <input type="checkbox" [(ngModel)]="isUnchanged"></label> |
<label>xlarge: <input type="checkbox" [(ngModel)]="isSpecial"></label>
<button (click)="setCurrentStyles()">Refresh currentStyles</button>
<br><br>
<div [ngStyle]="currentStyles">
This div should be {{ canSave ? "italic": "plain"}},
{{ isUnchanged ? "normal weight" : "bold" }} and,
{{ isSpecial ? "extra large": "normal size"}} after clicking "Refresh".</div>
<hr>
<h2>Built-in structural directives</h2>
<h3 id="ngIf">NgIf Binding</h3>
<div>
<p>If isActive is true, app-item-detail will render: </p>
<!-- #docregion NgIf-1 -->
<app-item-detail *ngIf="isActive" [item]="item"></app-item-detail>
<!-- #enddocregion NgIf-1 -->
<button (click)="isActiveToggle()">Toggle app-item-detail</button>
</div>
<p>If currentCustomer isn't null, say hello to Laura:</p>
<!-- #docregion NgIf-2 -->
<div *ngIf="currentCustomer">Hello, {{currentCustomer.name}}</div>
<!-- #enddocregion NgIf-2 -->
<p>nullCustomer is null by default. NgIf guards against null. Give it a value to show it:</p>
<!-- #docregion NgIf-2b -->
<div *ngIf="nullCustomer">Hello, <span>{{nullCustomer}}</span></div>
<!-- #enddocregion NgIf-2b -->
<button (click)="giveNullCustomerValue()">Give nullCustomer a value</button>
<h4>NgIf binding with template (no *)</h4>
<ng-template [ngIf]="currentItem">Add {{currentItem.name}} with template</ng-template>
<hr>
<h4>Show/hide vs. NgIf</h4>
<!-- #docregion NgIf-3 -->
<!-- isSpecial is true -->
<div [class.hidden]="!isSpecial">Show with class</div>
<div [class.hidden]="isSpecial">Hide with class</div>
<p>ItemDetail is in the DOM but hidden</p>
<app-item-detail [class.hidden]="isSpecial"></app-item-detail>
<div [style.display]="isSpecial ? 'block' : 'none'">Show with style</div>
<div [style.display]="isSpecial ? 'none' : 'block'">Hide with style</div>
<!-- #enddocregion NgIf-3 -->
<hr>
<h2 id="ngFor">NgFor Binding</h2>
<div class="box">
<!-- #docregion NgFor-1, NgFor-1-2 -->
<div *ngFor="let item of items">{{item.name}}</div>
<!-- #enddocregion NgFor-1, NgFor-1-2 -->
</div>
<p>*ngFor with ItemDetailComponent element</p>
<div class="box">
<!-- #docregion NgFor-2, NgFor-1-2 -->
<app-item-detail *ngFor="let item of items" [item]="item"></app-item-detail>
<!-- #enddocregion NgFor-2, NgFor-1-2 -->
</div>
<h4 id="ngFor-index">*ngFor with index</h4>
<p>with <i>semi-colon</i> separator</p>
<div class="box">
<!-- #docregion NgFor-3 -->
<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>
<!-- #enddocregion NgFor-3 -->
</div>
<p>with <i>comma</i> separator</p>
<div class="box">
<div *ngFor="let item of items, let i=index">{{i + 1}} - {{item.name}}</div>
</div>
<h4 id="ngFor-trackBy">*ngFor trackBy</h4>
<button (click)="resetList()">Reset items</button>
<button (click)="changeIds()">Change ids</button>
<button (click)="clearTrackByCounts()">Clear counts</button>
<p><i>without</i> trackBy</p>
<div class="box">
<div #noTrackBy *ngFor="let item of items">({{item.id}}) {{item.name}}</div>
<div id="noTrackByCnt" *ngIf="itemsNoTrackByCount" >
Item DOM elements change #{{itemsNoTrackByCount}} without trackBy
</div>
</div>
<p>with trackBy</p>
<div class="box">
<div #withTrackBy *ngFor="let item of items; trackBy: trackByItems">({{item.id}}) {{item.name}}</div>
<div id="withTrackByCnt" *ngIf="itemsWithTrackByCount">
Item DOM elements change #{{itemsWithTrackByCount}} with trackBy
</div>
</div>
<br><br><br>
<p>with trackBy and <i>semi-colon</i> separator</p>
<div class="box">
<!-- #docregion trackBy -->
<div *ngFor="let item of items; trackBy: trackByItems">
({{item.id}}) {{item.name}}
</div>
<!-- #enddocregion trackBy -->
</div>
<p>with trackBy and <i>comma</i> separator</p>
<div class="box">
<div *ngFor="let item of items, trackBy: trackByItems">({{item.id}}) {{item.name}}</div>
</div>
<p>with trackBy and <i>space</i> separator</p>
<div class="box">
<div *ngFor="let item of items trackBy: trackByItems">({{item.id}}) {{item.name}}</div>
</div>
<p>with <i>generic</i> trackById function</p>
<div class="box">
<div *ngFor="let item of items, trackBy: trackById">({{item.id}}) {{item.name}}</div>
</div>
<hr><h2>NgSwitch Binding</h2>
<p>Pick your favorite item</p>
<div>
<label *ngFor="let i of items">
<div><input type="radio" name="items" [(ngModel)]="currentItem" [value]="i">{{i.name}}
</div>
</label>
</div>
<!-- #docregion NgSwitch -->
<div [ngSwitch]="currentItem.feature">
<app-stout-item *ngSwitchCase="'stout'" [item]="currentItem"></app-stout-item>
<app-device-item *ngSwitchCase="'slim'" [item]="currentItem"></app-device-item>
<app-lost-item *ngSwitchCase="'vintage'" [item]="currentItem"></app-lost-item>
<app-best-item *ngSwitchCase="'bright'" [item]="currentItem"></app-best-item>
<!-- #enddocregion NgSwitch -->
<!-- #docregion NgSwitch-div -->
<div *ngSwitchCase="'bright'"> Are you as bright as {{currentItem.name}}?</div>
<!-- #enddocregion NgSwitch-div -->
<!-- #docregion NgSwitch -->
<app-unknown-item *ngSwitchDefault [item]="currentItem"></app-unknown-item>
</div>
<!-- #enddocregion NgSwitch -->

View File

@ -0,0 +1,115 @@
import { Component, OnInit } from '@angular/core';
import { Item } from './item';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
canSave = true;
isSpecial = true;
isUnchanged = true;
isActive = true;
nullCustomer = null;
currentCustomer = {
name: 'Laura'
};
item: Item; // defined to demonstrate template context precedence
items: Item[];
currentItem: Item;
// trackBy change counting
itemsNoTrackByCount = 0;
itemsWithTrackByCount = 0;
itemsWithTrackByCountReset = 0;
itemIdIncrement = 1;
ngOnInit() {
this.resetItems();
this.setCurrentClasses();
this.setCurrentStyles();
this.itemsNoTrackByCount = 0;
}
setUppercaseName(name: string) {
this.currentItem.name = name.toUpperCase();
}
// #docregion setClasses
currentClasses: {};
setCurrentClasses() {
// CSS classes: added/removed per current state of component properties
this.currentClasses = {
'saveable': this.canSave,
'modified': !this.isUnchanged,
'special': this.isSpecial
};
}
// #enddocregion setClasses
// #docregion setStyles
currentStyles: {};
setCurrentStyles() {
// CSS styles: set per current state of component properties
this.currentStyles = {
'font-style': this.canSave ? 'italic' : 'normal',
'font-weight': !this.isUnchanged ? 'bold' : 'normal',
'font-size': this.isSpecial ? '24px' : '12px'
};
}
// #enddocregion setStyles
isActiveToggle() {
this.isActive = !this.isActive;
}
giveNullCustomerValue() {
!(this.nullCustomer = null) ? (this.nullCustomer = 'Kelly') : (this.nullCustomer = null);
}
resetNullItem() {
this.nullCustomer = null;
}
resetItems() {
this.items = Item.items.map(item => item.clone());
this.currentItem = this.items[0];
this.item = this.currentItem;
}
resetList() {
this.resetItems()
this.itemsWithTrackByCountReset = 0;
this.itemsNoTrackByCount = ++this.itemsNoTrackByCount;
}
changeIds() {
this.items.forEach(i => i.id += 1 * this.itemIdIncrement);
this.itemsWithTrackByCountReset = -1;
this.itemsNoTrackByCount = ++this.itemsNoTrackByCount;
this.itemsWithTrackByCount = ++this.itemsWithTrackByCount;
}
clearTrackByCounts() {
this.resetItems();
this.itemsNoTrackByCount = 0;
this.itemsWithTrackByCount = 0;
this.itemIdIncrement = 1;
}
// #docregion trackByItems
trackByItems(index: number, item: Item): number { return item.id; }
// #enddocregion trackByItems
trackById(index: number, item: any): number { return item['id']; }
}

View File

@ -0,0 +1,34 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// #docregion import-forms-module
import { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular
// #enddocregion import-forms-module
import { AppComponent } from './app.component';
import { ItemDetailComponent } from './item-detail/item-detail.component';
import { ItemSwitchComponents } from './item-switch.component';
// #docregion import-forms-module
@NgModule({
// #enddocregion import-forms-module
declarations: [
AppComponent,
ItemDetailComponent,
ItemSwitchComponents
],
// #docregion import-forms-module
imports: [
BrowserModule,
FormsModule // <--- import into the NgModule
],
// #enddocregion import-forms-module
providers: [],
bootstrap: [AppComponent]
// #docregion import-forms-module
})
export class AppModule { }
// #enddocregion import-forms-module

View File

@ -0,0 +1,3 @@
<div>
<span>{{item?.name}}</span>
</div>

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ItemDetailComponent } from './item-detail.component';
describe('ItemDetailComponent', () => {
let component: ItemDetailComponent;
let fixture: ComponentFixture<ItemDetailComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ItemDetailComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ItemDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,17 @@
import { Component, Input } from '@angular/core';
import { Item } from '../item';
@Component({
selector: 'app-item-detail',
templateUrl: './item-detail.component.html',
styleUrls: ['./item-detail.component.css']
})
export class ItemDetailComponent {
@Input() item: Item;
constructor() { }
}

View File

@ -0,0 +1,50 @@
import { Component, Input } from '@angular/core';
import { Item } from './item';
@Component({
selector: 'app-stout-item',
template: `I'm a little {{item.name}}, short and stout!`
})
export class StoutItemComponent {
@Input() item: Item;
}
@Component({
selector: 'app-best-item',
template: `This is the brightest {{item.name}} in town.`
})
export class BestItemComponent {
@Input() item: Item;
}
@Component({
selector: 'app-device-item',
template: `Which is the slimmest {{item.name}}?`
})
export class DeviceItemComponent {
@Input() item: Item;
}
@Component({
selector: 'app-lost-item',
template: `Has anyone seen my {{item.name}}?`
})
export class LostItemComponent {
@Input() item: Item;
}
@Component({
selector: 'app-unknown-item',
template: `{{message}}`
})
export class UnknownItemComponent {
@Input() item: Item;
get message() {
return this.item && this.item.name ?
`${this.item.name} is strange and mysterious.` :
'A mystery wrapped in a fishbowl.';
}
}
export const ItemSwitchComponents =
[ StoutItemComponent, BestItemComponent, DeviceItemComponent, LostItemComponent, UnknownItemComponent ];

View File

@ -0,0 +1,30 @@
export class Item {
static nextId = 0;
static items: Item[] = [
new Item(
null,
'Teapot',
'stout'
),
new Item(1, 'Lamp', 'bright'),
new Item(2, 'Phone', 'slim' ),
new Item(3, 'Television', 'vintage' ),
new Item(4, 'Fishbowl')
];
constructor(
public id?: number,
public name?: string,
public feature?: string,
public url?: string,
public rate = 100,
) {
this.id = id ? id : Item.nextId++;
}
clone(): Item {
return Object.assign(new Item(), this);
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 32 KiB

View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>BuiltInDirectives</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>

View File

@ -0,0 +1,12 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));