docs(core): add an example of using ViewChildren

This commit is contained in:
vsavkin 2016-09-13 10:32:53 -07:00 committed by Evan Martin
parent c71e35cbf5
commit 60e49a7e4b
3 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,29 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {verifyNoBrowserErrors} from '../../../../../_common/e2e_util';
describe('viewChildren example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/core/di/ts/viewChildren/index.html');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query view children', () => {
expect(result.getText()).toEqual('panes: 1, 2');
button.click();
expect(result.getText()).toEqual('panes: 1, 2, 3');
});
});

View File

@ -0,0 +1,20 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Pane, ViewChildrenComp} from './view_children_example';
@NgModule({
imports: [BrowserModule],
declarations: [ViewChildrenComp, Pane],
bootstrap: [ViewChildrenComp]
})
export class AppModule {
}

View File

@ -0,0 +1,46 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion Component
import {AfterViewInit, Component, Directive, Input, QueryList, ViewChildren} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'example-app',
template: `
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow"></pane>
<button (click)="show()">Show 3</button>
<div>panes: {{serializedPanes}}</div>
`,
})
export class ViewChildrenComp implements AfterViewInit {
@ViewChildren(Pane) panes: QueryList<Pane>;
serializedPanes: string = '';
shouldShow = false;
show() { this.shouldShow = true; }
ngAfterViewInit() {
this.calculateSerializedPanes();
this.panes.changes.subscribe((r) => { this.calculateSerializedPanes(); });
}
calculateSerializedPanes() {
setTimeout(() => { this.serializedPanes = this.panes.map(p => p.id).join(', '); }, 0);
}
}
// #enddocregion