docs(core): add an example of using ViewChild

This commit is contained in:
vsavkin 2016-09-13 10:32:48 -07:00 committed by Evan Martin
parent 1348c65b0c
commit c71e35cbf5
3 changed files with 83 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('viewChild example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/core/di/ts/viewChild/index.html');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query view child', () => {
expect(result.getText()).toEqual('Selected: 1');
button.click();
expect(result.getText()).toEqual('Selected: 2');
});
});

View File

@ -0,0 +1,17 @@
/**
* @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, ViewChildComp} from './view_child_example';
@NgModule(
{imports: [BrowserModule], declarations: [ViewChildComp, Pane], bootstrap: [ViewChildComp]})
export class AppModule {
}

View File

@ -0,0 +1,37 @@
/**
* @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, ViewChild} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'example-app',
template: `
<pane id="1" *ngIf="shouldShow"></pane>
<pane id="2" *ngIf="!shouldShow"></pane>
<button (click)="toggle()">Toggle</button>
<div>Selected: {{selectedPane}}</div>
`,
})
export class ViewChildComp implements AfterViewInit {
@ViewChild(Pane)
set pane(v: Pane) {
setTimeout(() => { this.selectedPane = v.id; }, 0);
}
selectedPane: string = '';
shouldShow = true;
toggle() { this.shouldShow = !this.shouldShow; }
}
// #enddocregion