Skip to content

Commit

Permalink
feat(template): add a way to type context
Browse files Browse the repository at this point in the history
  • Loading branch information
waterplea committed Apr 29, 2021
1 parent 011afd9 commit 85ac276
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ Please see [extensive demo](https://codesandbox.io/s/github/TinkoffCreditSystems

You can also [read about this concept in detail](https://medium.com/angular-in-depth/agnostic-components-in-angular-2427923b742d).

### Adding type to template context

You can use `polymorpehus` directive to add type to template context:

```typescript
readonly context!: { $implicit: number };
```

```html
<ng-template #temlate="polymorpheus" [polymorpheus]="context" let-item>
{{ item.toFixed(2) }} <-- type 'number'
</ng-template>
```

## Open-source

Do you also want to open-source something, but hate the collateral work?
Expand Down
10 changes: 10 additions & 0 deletions projects/ng-polymorpheus/src/directives/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import {ChangeDetectorRef, Directive, Inject, Self, TemplateRef} from '@angular/
@Directive({
selector: 'ng-template[polymorpheus]',
exportAs: 'polymorpheus',
inputs: ['polymorpheus'],
})
export class PolymorpheusTemplate<T extends object> {
polymorpheus!: T;

constructor(
@Inject(TemplateRef)
@Self()
Expand All @@ -18,4 +21,11 @@ export class PolymorpheusTemplate<T extends object> {
check() {
this.changeDetectorRef.markForCheck();
}

static ngTemplateContextGuard<T extends {}>(
_dir: PolymorpheusTemplate<T>,
_ctx: any,
): _ctx is T {
return true;
}
}
9 changes: 6 additions & 3 deletions projects/ng-polymorpheus/src/outlet/outlet.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ describe('PolymorpheusOutlet', () => {
}

@Component({
template: `
Component: {{ context.$implicit }}
`,
template: ` Component: {{ context.$implicit }} `,
changeDetection: ChangeDetectionStrategy.OnPush,
})
class ComponentContent {
Expand Down Expand Up @@ -119,6 +117,11 @@ describe('PolymorpheusOutlet', () => {
expect(text()).toBe('');
});

it('Static type check exists', () => {
// @ts-ignore
expect(PolymorpheusTemplate.ngTemplateContextGuard()).toBe(true);
});

describe('Primitive', () => {
it('Works with strings', () => {
testComponent.content = 'string';
Expand Down

0 comments on commit 85ac276

Please sign in to comment.