Skip to content
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

feat(elements): add custom element support, prototype AIO #22413

Closed
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions .pullapprove.yml
Expand Up @@ -7,6 +7,7 @@
#
# alexeagle - Alex Eagle
# alxhub - Alex Rickabaugh
# andrewseguin - Andrew Seguin
# brocco - Mike Brocchi
# chuckjaz - Chuck Jazdzewski
# filipesilva - Filipe Silva
Expand Down Expand Up @@ -302,6 +303,16 @@ groups:
- IgorMinar #fallback
- mhevery #fallback

elements:
conditions:
files:
- "packages/elements/*"
users:
- andrewseguin #primary
- gkalpak
- IgorMinar #fallback
- mhevery #fallback

benchpress:
conditions:
files:
Expand Down
1 change: 1 addition & 0 deletions BUILD.bazel
Expand Up @@ -40,6 +40,7 @@ filegroup(
"reflect-metadata",
"source-map-support",
"minimist",
"@webcomponents/custom-elements",
"tslib",
] for ext in [
"*.js",
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Expand Up @@ -212,6 +212,7 @@ The following is the list of supported scopes:
* **compiler**
* **compiler-cli**
* **core**
* **elements**
* **forms**
* **http**
* **language-service**
Expand Down
4 changes: 3 additions & 1 deletion aio/.angular-cli.json
Expand Up @@ -13,7 +13,9 @@
"app/search/search-worker.js",
"favicon.ico",
"pwa-manifest.json",
"google385281288605d160.html"
"google385281288605d160.html",
{ "glob": "custom-elements.min.js", "input": "../node_modules/@webcomponents/custom-elements", "output": "./assets/js" },
{ "glob": "native-shim.js", "input": "../node_modules/@webcomponents/custom-elements/src", "output": "./assets/js" }
],
"index": "index.html",
"main": "main.ts",
Expand Down
65 changes: 65 additions & 0 deletions aio/content/guide/custom-elements.md
@@ -0,0 +1,65 @@
# Elements

## Release Status

**Angular Labs Project** - experimental and unstable. **Breaking Changes Possible**

Targeted to land in the [6.x release cycle](https://github.com/angular/angular/blob/master/docs/RELEASE_SCHEDULE.md) of Angular - subject to change

## Overview

Elements provides an API that allows developers to register Angular Components as Custom Elements
("Web Components"), and bridges the built-in DOM API to Angular's component interface and change
detection APIs.

```ts
//hello-world.ts
import { Component, Input, NgModule } from '@angular/core';

@Component({
selector: 'hello-world',
template: `<h1>Hello {{name}}</h1>`
})
export class HelloWorld {
@Input() name: string = 'World!';
}

@NgModule({
declarations: [ HelloWorld ],
entryComponents: [ HelloWorld ]
})
export class HelloWorldModule {}
```

```ts
//app.component.ts
import { Component, NgModuleRef } from '@angular/core';
import { createNgElementConstructor } from '@angular/elements';

import { HelloWorld } from './hello-world';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(injector: Injector) {
const NgElementConstructor = createNgElementConstructor(HelloWorld, {injector});
customElements.register('hello-world', NgElementConstructor);
}
}

```
Once registered, these components can be used just like built-in HTML elements, because they *are*
HTML Elements!

They can be used in any HTML page:

```html
<hello-world name="Angular"></hello-world>
<hello-world name="Typescript"></hello-world>
```

Custom Elements are "self-bootstrapping" - they are automatically started when they are added to the
DOM, and automatically destroyed when removed from the DOM.
7 changes: 6 additions & 1 deletion aio/content/navigation.json
Expand Up @@ -198,7 +198,7 @@
"url": "guide/structural-directives",
"title": "Structural Directives",
"tooltip": "Structural directives manipulate the layout of the page."
},
},
{
"url": "guide/pipes",
"title": "Pipes",
Expand Down Expand Up @@ -457,6 +457,11 @@
}
]
},
{
"url": "guide/custom-elements",
"title": "Custom Elements",
"tooltip": "Using Angular Components as Custom Elements."
},
{
"title": "Service Workers",
"tooltip": "Angular service workers: Controlling caching of application resources.",
Expand Down
2 changes: 2 additions & 0 deletions aio/package.json
Expand Up @@ -75,6 +75,7 @@
"@angular/common": "^5.2.0",
"@angular/compiler": "^5.2.0",
"@angular/core": "^5.2.0",
"@angular/elements": "file:../dist/packages-dist/elements",
"@angular/forms": "^5.2.0",
"@angular/http": "^5.2.0",
"@angular/material": "^5.0.0-rc.1",
Expand All @@ -83,6 +84,7 @@
"@angular/platform-server": "^5.2.0",
"@angular/router": "^5.2.0",
"@angular/service-worker": "^1.0.0-beta.16",
"@webcomponents/custom-elements": "^1.0.8",
"classlist.js": "^1.1.20150312",
"core-js": "^2.4.1",
"jasmine": "^2.6.0",
Expand Down
6 changes: 3 additions & 3 deletions aio/scripts/_payload-limits.json
Expand Up @@ -2,9 +2,9 @@
"aio": {
"master": {
"uncompressed": {
"inline": 1602,
"main": 459119,
"polyfills": 40264,
"inline": 2062,
"main": 467103,
"polyfills": 40274,
"embedded": 71711,
"prettify": 14888
}
Expand Down
7 changes: 0 additions & 7 deletions aio/src/app/app.component.spec.ts
Expand Up @@ -7,7 +7,6 @@ import { MatProgressBar, MatSidenav } from '@angular/material';
import { By } from '@angular/platform-browser';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { timer } from 'rxjs/observable/timer';
import 'rxjs/add/operator/mapTo';

Expand All @@ -16,7 +15,6 @@ import { AppModule } from './app.module';
import { DocumentService } from 'app/documents/document.service';
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
import { Deployment } from 'app/shared/deployment.service';
import { EmbedComponentsService } from 'app/embed-components/embed-components.service';
import { GaService } from 'app/shared/ga.service';
import { LocationService } from 'app/shared/location.service';
import { Logger } from 'app/shared/logger.service';
Expand Down Expand Up @@ -1280,7 +1278,6 @@ function createTestingModule(initialUrl: string, mode: string = 'stable') {
imports: [ AppModule ],
providers: [
{ provide: APP_BASE_HREF, useValue: '/' },
{ provide: EmbedComponentsService, useClass: TestEmbedComponentsService },
{ provide: GaService, useClass: TestGaService },
{ provide: HttpClient, useClass: TestHttpClient },
{ provide: LocationService, useFactory: () => mockLocationService },
Expand All @@ -1295,10 +1292,6 @@ function createTestingModule(initialUrl: string, mode: string = 'stable') {
});
}

class TestEmbedComponentsService {
embedInto = jasmine.createSpy('embedInto').and.returnValue(of([]));
}

class TestGaService {
locationChanged = jasmine.createSpy('locationChanged');
}
Expand Down
50 changes: 0 additions & 50 deletions aio/src/app/app.module.spec.ts
@@ -1,50 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { AppModule } from 'app/app.module';
import { ComponentsOrModulePath, EMBEDDED_COMPONENTS } from 'app/embed-components/embed-components.service';
import { embeddedComponents } from 'app/embedded/embedded.module';

describe('AppModule', () => {
let componentsMap: {[multiSelectorstring: string]: ComponentsOrModulePath};

beforeEach(() => {
TestBed.configureTestingModule({imports: [AppModule]});
componentsMap = TestBed.get(EMBEDDED_COMPONENTS);
});

it('should provide a map of selectors to embedded components (or module)', () => {
const allSelectors = Object.keys(componentsMap);

expect(allSelectors.length).toBeGreaterThan(1);
allSelectors.forEach(selector => {
const value = componentsMap[selector];
const isArrayOrString = Array.isArray(value) || (typeof value === 'string');
expect(isArrayOrString).toBe(true);
});
});

it('should provide a list of eagerly-loaded embedded components', () => {

const eagerConfig = Object.keys(componentsMap).filter(selector => Array.isArray(componentsMap[selector]));
expect(eagerConfig.length).toBeGreaterThan(0);

const eagerSelectors = eagerConfig.reduce<string[]>((selectors, config) => selectors.concat(config.split(',')), []);
expect(eagerSelectors.length).toBeGreaterThan(0);

// For example...
expect(eagerSelectors).toContain('aio-toc');
expect(eagerSelectors).toContain('aio-announcement-bar');
});

it('should provide a list of lazy-loaded embedded components', () => {
const lazySelector = Object.keys(componentsMap).find(selector => selector.includes('code-example'))!;
const selectorCount = lazySelector.split(',').length;

expect(lazySelector).not.toBeNull();
expect(selectorCount).toBe(embeddedComponents.length);

// For example...
expect(lazySelector).toContain('code-example');
expect(lazySelector).toContain('code-tabs');
expect(lazySelector).toContain('live-example');
});
});
39 changes: 5 additions & 34 deletions aio/src/app/app.module.ts
Expand Up @@ -11,12 +11,7 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatToolbarModule } from '@angular/material/toolbar';

import { ROUTES } from '@angular/router';


import { AnnouncementBarComponent } from 'app/embedded/announcement-bar/announcement-bar.component';
import { AppComponent } from 'app/app.component';
import { EMBEDDED_COMPONENTS, EmbeddedComponentsMap } from 'app/embed-components/embed-components.service';
import { CustomIconRegistry, SVG_ICONS } from 'app/shared/custom-icon-registry';
import { Deployment } from 'app/shared/deployment.service';
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
Expand All @@ -42,14 +37,10 @@ import { TocService } from 'app/shared/toc.service';
import { CurrentDateToken, currentDateProvider } from 'app/shared/current-date';
import { WindowToken, windowProvider } from 'app/shared/window';

import { EmbedComponentsModule } from 'app/embed-components/embed-components.module';
import { CustomElementsModule } from 'app/custom-elements/custom-elements.module';
import { SharedModule } from 'app/shared/shared.module';
import { SwUpdatesModule } from 'app/sw-updates/sw-updates.module';


// The path to the `EmbeddedModule`.
const embeddedModulePath = 'app/embedded/embedded.module#EmbeddedModule';

// These are the hardcoded inline svg sources to be used by the `<mat-icon>` component
export const svgIconProviders = [
{
Expand Down Expand Up @@ -100,18 +91,17 @@ export const svgIconProviders = [
imports: [
BrowserModule,
BrowserAnimationsModule,
EmbedComponentsModule,
CustomElementsModule,
HttpClientModule,
MatButtonModule,
MatIconModule,
MatProgressBarModule,
MatSidenavModule,
MatToolbarModule,
SwUpdatesModule,
SharedModule
SharedModule,
],
declarations: [
AnnouncementBarComponent,
AppComponent,
DocViewerComponent,
DtComponent,
Expand Down Expand Up @@ -142,27 +132,8 @@ export const svgIconProviders = [
TocService,
{ provide: CurrentDateToken, useFactory: currentDateProvider },
{ provide: WindowToken, useFactory: windowProvider },

{
provide: EMBEDDED_COMPONENTS,
useValue: {
/* tslint:disable: max-line-length */
'aio-announcement-bar': [AnnouncementBarComponent],
'aio-toc': [TocComponent],
'aio-api-list, aio-contributor-list, aio-file-not-found-search, aio-resource-list, code-example, code-tabs, current-location, live-example': embeddedModulePath,
/* tslint:enable: max-line-length */
} as EmbeddedComponentsMap,
},
{
// This is currently the only way to get `@angular/cli`
// to split `EmbeddedModule` into a separate chunk :(
provide: ROUTES,
useValue: [{ path: '/embedded', loadChildren: embeddedModulePath }],
multi: true,
},
],
entryComponents: [ AnnouncementBarComponent, TocComponent ],
entryComponents: [ TocComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
export class AppModule { }
@@ -0,0 +1,15 @@
import { NgModule, Type } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { SharedModule } from '../../shared/shared.module';
import { AnnouncementBarComponent } from './announcement-bar.component';
import { WithCustomElementComponent } from '../element-registry';

@NgModule({
imports: [ CommonModule, SharedModule, HttpClientModule ],
declarations: [ AnnouncementBarComponent ],
entryComponents: [ AnnouncementBarComponent ],
})
export class AnnouncementBarModule implements WithCustomElementComponent {
customElementComponent: Type<any> = AnnouncementBarComponent;
}
Expand Up @@ -4,7 +4,9 @@ import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ApiListComponent } from './api-list.component';
import { ApiItem, ApiSection, ApiService } from './api.service';
import { LocationService } from 'app/shared/location.service';
import { SharedModule } from 'app/shared/shared.module';
import { Logger } from 'app/shared/logger.service';
import { MockLogger } from 'testing/logger.service';
import { ApiListModule } from './api-list.module';

describe('ApiListComponent', () => {
let component: ApiListComponent;
Expand All @@ -13,10 +15,10 @@ describe('ApiListComponent', () => {

beforeEach(() => {
TestBed.configureTestingModule({
imports: [ SharedModule ],
declarations: [ ApiListComponent ],
imports: [ ApiListModule ],
providers: [
{ provide: ApiService, useClass: TestApiService },
{ provide: Logger, useClass: MockLogger },
{ provide: LocationService, useClass: TestLocationService }
]
});
Expand All @@ -37,11 +39,11 @@ describe('ApiListComponent', () => {
let badItem: ApiItem|undefined;
expect(filtered.length).toBeGreaterThan(0, 'expected something');
expect(filtered.every(section => section.items.every(
item => {
const ok = item.show === itemTest(item);
if (!ok) { badItem = item; }
return ok;
}
item => {
const ok = item.show === itemTest(item);
if (!ok) { badItem = item; }
return ok;
}
))).toBe(true, `${label} fail: ${JSON.stringify(badItem, null, 2)}`);
});
}
Expand Down