8000 feat(common): ngLet directive by ibarsi · Pull Request #25472 · angular/angular · GitHub
[go: up one dir, main page]

Skip to content

feat(common): ngLet directive #25472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/common/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export {registerLocaleData} from './i18n/locale_data';
export {Plural, NumberFormatStyle, FormStyle, Time, TranslationWidth, FormatWidth, NumberSymbol, WeekDay, getNumberOfCurrencyDigits, getCurrencySymbol, getLocaleDayPeriods, getLocaleDayNames, getLocaleMonthNames, getLocaleId, getLocaleEraNames, getLocaleWeekEndRange, getLocaleFirstDayOfWeek, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocalePluralCase, getLocaleTimeFormat, getLocaleNumberSymbol, getLocaleNumberFormat, getLocaleCurrencyName, getLocaleCurrencySymbol} from './i18n/locale_data_api';
export {parseCookieValue as ɵparseCookieValue} from './cookie';
export {CommonModule, DeprecatedI18NPipesModule} from './common_module';
export {NgClass, NgForOf, NgForOfContext, NgIf, NgIfContext, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet, NgComponentOutlet} from './directives/index';
export {NgClass, NgForOf, NgForOfContext, NgIf, NgIfContext, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet, NgComponentOutlet, NgLet, NgLetContext} from './directives/index';
export {DOCUMENT} from './dom_tokens';
export {AsyncPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, LowerCasePipe, CurrencyPipe, DecimalPipe, PercentPipe, SlicePipe, UpperCasePipe, TitleCasePipe, KeyValuePipe, KeyValue} from './pipes/index';
export {DeprecatedDatePipe, DeprecatedCurrencyPipe, DeprecatedDecimalPipe, DeprecatedPercentPipe} from './pipes/deprecated/index';
Expand Down
16 changes: 5 additions & 11 deletions packages/common/src/directives/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {NgClass} from './ng_class';
import {NgComponentOutlet} from './ng_component_outlet';
import {NgForOf, NgForOfContext} from './ng_for_of';
import {NgIf, NgIfContext} from './ng_if';
import {NgLet, NgLetContext} from './ng_let';
import {NgPlural, NgPluralCase} from './ng_plural';
import {NgStyle} from './ng_style';
import {NgSwitch, NgSwitchCase, NgSwitchDefault} from './ng_switch';
Expand All @@ -24,6 +25,8 @@ export {
NgForOfContext,
NgIf,
NgIfContext,
NgLet,
NgLetContext,
NgPlural,
NgPluralCase,
NgStyle,
Expand All @@ -40,15 +43,6 @@ export {
* application.
*/
export const COMMON_DIRECTIVES: Provider[] = [
NgClass,
NgComponentOutlet,
NgForOf,
NgIf,
NgTemplateOutlet,
NgStyle,
NgSwitch,
NgSwitchCase,
NgSwitchDefault,
NgPlural,
NgPluralCase,
NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase,
NgSwitchDefault, NgPlural, NgPluralCase, NgLet
];
74 changes: 74 additions & 0 deletions packages/common/src/directives/ng_let.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @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 {Directive, Input, OnInit, TemplateRef, ViewContainerRef} from '@angular/core';



/**
* Exposes a stored expression value to its child view.
*
* `ngLet` evaluates the expression and, if stored in a variable, provides the result to its child
* view.
*
*
* @usageNotes
*
* ### Storing falsy result in a variable
*
* `ngIf` supports the common use case of storing a value in a variable and exposing it to its child
* view.
*
* {@example common/ngIf/ts/module.ts region='NgIfAs'}
*
* This works well for most cases. However, if the value stored is falsy (ie. `false`, `0`, `''`,
* etc)
* the child view will not be rendered. This can be problematic if the stored value is required to
* be displayed,
* or provided as an argument to an output or DOM event.
*
* `ngLet` works around this issue by always rendering the child view, regardless of the result of
* its expression.
*
* ### Semantic meaning
*
* Even in the cases where `ngIf` works, some semantic meaning is lost. Reading the code doesn't
* communicate whether
* the auther intended contitional rendering or simply needed to expose the result of the expression
* to its child view.
*
* `ngLet` explicitly communicates semantic meaning, illustrating that the intent of the author's
* code was to expose the
* result of the expression, not conditional rendering.
*
* ### Syntax
*
* Simple form:
* - `<div *ngLet="condition as value">{{value}}</div>`
* - `<ng-template [ngLet]="condition as value"><div>{{value}}</div></ng-template>`
*
*
*/
@Directive({selector: '[ngLet]'})
export class NgLet implements OnInit {
private _context: NgLetContext = new NgLetContext();

constructor(
private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef<NgLetContext>, ) {
}

@Input()
set ngLet(value: any) { this._context.$implicit = this._context.ngLet = value; }

ngOnInit() { this._viewContainer.createEmbeddedView(this._templateRef, this._context); }
}

export class NgLetContext {
public $implicit: any = null;
public ngLet: any = null;
}
74 changes: 74 additions & 0 deletions packages/common/test/directives/ng_let.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @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 {CommonModule} from '@angular/common';
import {Component, EventEmitter} from '@angular/core';
import {ComponentFixture, TestBed, async} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {expect} from '@angular/platform-browser/testing/src/matchers';

{
describe('ngLet directive', () => {
let fixture: ComponentFixture<any>;

function getComponent(): TestComponent { return fixture.componentInstance; }

afterEach(() => { fixture = null !; });

beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [CommonModule],
});
});

it('should support binding to observable using as', async(() => {
Copy link
Contributor
@jotatoledo jotatoledo Aug 21, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dont use EventEmitter for the purpose of an Observable instance. Use a Subject or similar.

const template = '<span *ngLet="observableStringValue | async as val">{{val}}</span>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('');

getComponent().observableStringValue.emit('some string');
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('some string');
}));

it('should support binding to variable using as', async(() => {
const template = '<span *ngLet="stringValue as val">{{val}}</span>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('some string');
}));

it('should support binding to variable using let', async(() => {
const template = '<span *ngLet="stringValue; let v">{{v}}</span>';

fixture = createTestComponent(template);

fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('some string');

getComponent().stringValue = 'some other string';
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('some other string');
}));
});
}

@Component({selector: 'test-cmp', template: ''})
class TestComponent {
stringValue: string = 'some string';
observableStringValue: EventEmitter<any> = new EventEmitter();
}

function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}})
.createComponent(TestComponent);
}
10 changes: 10 additions & 0 deletions tools/public_api_guard/common/common.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,16 @@ export declare class NgIfContext {
ngIf: any;
}

export declare class NgLet {
ngLet: any;
constructor(_viewContainer: ViewContainerRef, _templateRef: TemplateRef<NgLetContext>);
}

export declare class NgLetContext {
$implicit: any;
ngLet: any;
}

/** @experimental */
export declare class NgLocaleLocalization extends NgLocalization {
/** @deprecated */ protected deprecatedPluralFn?: ((locale: string, value: string | number) => Plural) | null | undefined;
Expand Down
0