├── .angular-cli.json ├── .editorconfig ├── .gitignore ├── README.md ├── e2e ├── app.e2e-spec.ts ├── app.po.ts └── tsconfig.e2e.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── protractor.conf.js ├── src ├── @angular │ └── elements │ │ ├── index.ts │ │ ├── package.json │ │ ├── public_api.ts │ │ ├── rollup.config.js │ │ ├── src │ │ ├── extract-projectable-nodes.ts │ │ ├── ng-element-application-context.ts │ │ ├── ng-element-constructor.ts │ │ ├── ng-element.ts │ │ ├── ng-elements.ts │ │ ├── register-as-custom-elements.ts │ │ ├── utils.ts │ │ └── version.ts │ │ └── tsconfig-build.json ├── app │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── common │ │ └── material.module.ts │ ├── like-button │ │ ├── like-button.component.html │ │ ├── like-button.component.scss │ │ ├── like-button.component.spec.ts │ │ └── like-button.component.ts │ ├── module-shell │ │ ├── module-shell.component.html │ │ ├── module-shell.component.scss │ │ ├── module-shell.component.spec.ts │ │ └── module-shell.component.ts │ ├── page1 │ │ ├── page1.component.html │ │ ├── page1.component.scss │ │ ├── page1.component.spec.ts │ │ └── page1.component.ts │ ├── page2 │ │ ├── page2.component.html │ │ ├── page2.component.scss │ │ ├── page2.component.spec.ts │ │ └── page2.component.ts │ └── routes.ts ├── assets │ └── .gitkeep ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── now.json ├── polyfills.ts ├── styles.scss ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── typings.d.ts ├── tsconfig.json ├── tslint.json └── yarn.lock /.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "angular-elements-sample" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": [ 11 | "assets", 12 | "favicon.ico", 13 | "now.json" 14 | ], 15 | "index": "index.html", 16 | "main": "main.ts", 17 | "polyfills": "polyfills.ts", 18 | "test": "test.ts", 19 | "tsconfig": "tsconfig.app.json", 20 | "testTsconfig": "tsconfig.spec.json", 21 | "prefix": "app", 22 | "styles": [ 23 | "styles.scss" 24 | ], 25 | "scripts": [], 26 | "environmentSource": "environments/environment.ts", 27 | "environments": { 28 | "dev": "environments/environment.ts", 29 | "prod": "environments/environment.prod.ts" 30 | } 31 | } 32 | ], 33 | "e2e": { 34 | "protractor": { 35 | "config": "./protractor.conf.js" 36 | } 37 | }, 38 | "lint": [ 39 | { 40 | "project": "src/tsconfig.app.json", 41 | "exclude": "**/node_modules/**" 42 | }, 43 | { 44 | "project": "src/tsconfig.spec.json", 45 | "exclude": "**/node_modules/**" 46 | }, 47 | { 48 | "project": "e2e/tsconfig.e2e.json", 49 | "exclude": "**/node_modules/**" 50 | } 51 | ], 52 | "test": { 53 | "karma": { 54 | "config": "./karma.conf.js" 55 | } 56 | }, 57 | "defaults": { 58 | "styleExt": "scss", 59 | "component": {} 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | testem.log 34 | /typings 35 | 36 | # e2e 37 | /e2e/*.js 38 | /e2e/*.map 39 | 40 | # System Files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AngularElementsSample 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.6.0. and demonstrates how web components can be generated using standard angular components 4 | 5 | ## Development server 6 | 7 | Run `npm start` for a dev server. Navigate to `http://localhost:4200/`. 8 | 9 | 10 | ## How to implement 11 | Please review the commits, I've created step by step commits. 12 | 13 | 14 | ## How to use 15 | After build `npm run build` there will be three js files (inline.bundle.js, main.bundle.js, styles.bundle.js) include them in any html file and you will have access to your web components, created in angular! 16 | 17 | 18 | ## @angular/elements 19 | this package is coppied from angular repository labs/elements branch, it's folder can be removed after this package will be released and will be available on npm 20 | 21 | 22 | ## Summarize 23 | We don't have bootstrap component in AppModule, instead of that we can have any number of entry components and they all will be web components! 24 | 25 | For demonstration I've commented standard app-root component in index.html and placed multiple app-like-button components. 26 | 27 | To create more web components using angular, just generate new component `ng g component my-new-comp` and place in AppModule's entryComponent's list, thats it, really simple :) 28 | 29 | ## Video 30 | [![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/ljsOPm4MMEo/0.jpg)](https://www.youtube.com/watch?v=ljsOPm4MMEo) 31 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('angular-elements-sample App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Welcome to app!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular/cli'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular/cli/plugins/karma') 14 | ], 15 | client:{ 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | reports: [ 'html', 'lcovonly' ], 20 | fixWebpackSourcePaths: true 21 | }, 22 | angularCli: { 23 | environment: 'dev' 24 | }, 25 | reporters: ['progress', 'kjhtml'], 26 | port: 9876, 27 | colors: true, 28 | logLevel: config.LOG_INFO, 29 | autoWatch: true, 30 | browsers: ['Chrome'], 31 | singleRun: false 32 | }); 33 | }; 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-elements-sample", 3 | "alias": "angular-elements-sample", 4 | "version": "0.0.0", 5 | "license": "MIT", 6 | "scripts": { 7 | "ng": "ng", 8 | "start": "ng serve --port=4201 --sourcemap=false --vendor-chunk=true --common-chunk=false", 9 | "build": "ng build --prod --sourcemap=false --vendor-chunk=true --common-chunk=false --output-hashing none", 10 | "alias": "cd ./dist && now alias", 11 | "deploy": "yarn build && now ./dist -p", 12 | "test": "ng test", 13 | "lint": "ng lint", 14 | "e2e": "ng e2e" 15 | }, 16 | "private": true, 17 | "dependencies": { 18 | "@angular/animations": "^5.1.0", 19 | "@angular/cdk": "^5.0.0", 20 | "@angular/common": "^5.0.0", 21 | "@angular/compiler": "^5.0.0", 22 | "@angular/core": "^5.0.0", 23 | "@angular/forms": "^5.0.0", 24 | "@angular/http": "^5.0.0", 25 | "@angular/material": "^5.0.0", 26 | "@angular/platform-browser": "^5.0.0", 27 | "@angular/platform-browser-dynamic": "^5.0.0", 28 | "@angular/router": "^5.0.0", 29 | "@webcomponents/custom-elements": "^1.0.6", 30 | "core-js": "^2.4.1", 31 | "rxjs": "^5.5.2", 32 | "zone.js": "^0.8.14" 33 | }, 34 | "devDependencies": { 35 | "@angular/cli": "1.6.0", 36 | "@angular/compiler-cli": "^5.0.0", 37 | "@angular/language-service": "^5.0.0", 38 | "@types/jasmine": "~2.5.53", 39 | "@types/jasminewd2": "~2.0.2", 40 | "@types/node": "~6.0.60", 41 | "codelyzer": "^4.0.1", 42 | "jasmine-core": "~2.6.2", 43 | "jasmine-spec-reporter": "~4.1.0", 44 | "karma": "~1.7.0", 45 | "karma-chrome-launcher": "~2.1.1", 46 | "karma-cli": "~1.0.1", 47 | "karma-coverage-istanbul-reporter": "^1.2.1", 48 | "karma-jasmine": "~1.1.0", 49 | "karma-jasmine-html-reporter": "^0.2.2", 50 | "protractor": "~5.1.2", 51 | "ts-node": "~3.2.0", 52 | "tslint": "~5.7.0", 53 | "typescript": "~2.4.2" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/@angular/elements/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | // This file is not used to build this module. It is only used during editing 10 | // by the TypeScript language service and during build for verification. `ngc` 11 | // replaces this file with production index.ts when it rewrites private symbol 12 | // names. 13 | 14 | export * from './public_api'; 15 | -------------------------------------------------------------------------------- /src/@angular/elements/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@angular/elements", 3 | "version": "0.0.0-PLACEHOLDER", 4 | "description": "Angular - library for using Angular in a web browser", 5 | "main": "./bundles/elements.umd.js", 6 | "module": "./esm5/elements.js", 7 | "es2015": "./esm2015/elements.js", 8 | "typings": "./elements.d.ts", 9 | "author": "angular", 10 | "license": "MIT", 11 | "dependencies": { 12 | "tslib": "^1.7.1" 13 | }, 14 | "peerDependencies": { 15 | "@angular/core": "0.0.0-PLACEHOLDER", 16 | "@angular/platform-browser": "0.0.0-PLACEHOLDER" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/angular/angular.git" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/@angular/elements/public_api.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | /** 10 | * @module 11 | * @description 12 | * Entry point for all public APIs of the `elements` package. 13 | */ 14 | export {NgElement, NgElementWithProps} from './src/ng-element'; 15 | export {NgElementConstructor} from './src/ng-element-constructor'; 16 | export {registerAsCustomElements} from './src/register-as-custom-elements'; 17 | export {VERSION} from './src/version'; 18 | 19 | // This file only reexports content of the `src` folder. Keep it that way. 20 | -------------------------------------------------------------------------------- /src/@angular/elements/rollup.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | const resolve = require('rollup-plugin-node-resolve'); 10 | const sourcemaps = require('rollup-plugin-sourcemaps'); 11 | 12 | const globals = { 13 | '@angular/core': 'ng.core', 14 | '@angular/platform-browser': 'ng.platformBrowser', 15 | 'rxjs/Subscription': 'Rx', 16 | }; 17 | 18 | module.exports = { 19 | entry: '../../dist/packages-dist/elements/esm5/elements.js', 20 | dest: '../../dist/packages-dist/elements/bundles/elements.umd.js', 21 | format: 'umd', 22 | exports: 'named', 23 | amd: {id: '@angular/elements'}, 24 | moduleName: 'ng.elements', 25 | plugins: [resolve(), sourcemaps()], 26 | external: Object.keys(globals), 27 | globals: globals 28 | }; 29 | -------------------------------------------------------------------------------- /src/@angular/elements/src/extract-projectable-nodes.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | // NOTE: This is a (slightly improved) version of what is used in ngUpgrade's 10 | // `DowngradeComponentAdapter`. 11 | // TODO(gkalpak): Investigate if it makes sense to share the code. 12 | 13 | import {isElement, matchesSelector} from './utils'; 14 | 15 | export function extractProjectableNodes(host: HTMLElement, ngContentSelectors: string[]): Node[][] { 16 | const nodes = host.childNodes; 17 | const projectableNodes: Node[][] = ngContentSelectors.map(() => []); 18 | let wildcardIndex = -1; 19 | 20 | ngContentSelectors.some((selector, i) => { 21 | if (selector === '*') { 22 | wildcardIndex = i; 23 | return true; 24 | } 25 | return false; 26 | }); 27 | 28 | for (let i = 0, ii = nodes.length; i < ii; ++i) { 29 | const node = nodes[i]; 30 | const ngContentIndex = findMatchingIndex(node, ngContentSelectors, wildcardIndex); 31 | 32 | if (ngContentIndex !== -1) { 33 | projectableNodes[ngContentIndex].push(node); 34 | } 35 | } 36 | 37 | return projectableNodes; 38 | } 39 | 40 | function findMatchingIndex(node: Node, selectors: string[], defaultIndex: number): number { 41 | let matchingIndex = defaultIndex; 42 | 43 | if (isElement(node)) { 44 | selectors.some((selector, i) => { 45 | if ((selector !== '*') && matchesSelector(node, selector)) { 46 | matchingIndex = i; 47 | return true; 48 | } 49 | return false; 50 | }); 51 | } 52 | 53 | return matchingIndex; 54 | } 55 | -------------------------------------------------------------------------------- /src/@angular/elements/src/ng-element-application-context.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {ApplicationRef, Injector, NgZone} from '@angular/core'; 10 | 11 | export class NgElementApplicationContext { 12 | applicationRef = this.injector.get(ApplicationRef); 13 | ngZone = this.injector.get(NgZone); 14 | 15 | constructor(public injector: Injector) {} 16 | 17 | runInNgZone(cb: () => R): R { return this.ngZone.run(cb); } 18 | } 19 | -------------------------------------------------------------------------------- /src/@angular/elements/src/ng-element-constructor.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {ComponentFactory, EventEmitter} from '@angular/core'; 10 | 11 | import {NgElementImpl, NgElementWithProps} from './ng-element'; 12 | import {NgElementApplicationContext} from './ng-element-application-context'; 13 | import {camelToKebabCase, throwError} from './utils'; 14 | 15 | /** 16 | * TODO(gkalpak): Add docs. 17 | * @experimental 18 | */ 19 | export interface NgElementConstructor { 20 | readonly is: string; 21 | readonly observedAttributes: string[]; 22 | 23 | upgrade(host: HTMLElement): NgElementWithProps; 24 | 25 | new (): NgElementWithProps; 26 | } 27 | 28 | export interface NgElementConstructorInternal extends NgElementConstructor { 29 | readonly onConnected: EventEmitter>; 30 | readonly onDisconnected: EventEmitter>; 31 | upgrade(host: HTMLElement, ignoreUpgraded?: boolean): NgElementWithProps; 32 | } 33 | 34 | type WithProperties

= { 35 | [property in keyof P]: P[property] 36 | }; 37 | 38 | // For more info on `PotentialCustomElementName` rules see: 39 | // https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name 40 | const PCEN_RE = createPcenRe(); 41 | const PCEN_BLACKLIST = [ 42 | 'annotation-xml', 43 | 'color-profile', 44 | 'font-face', 45 | 'font-face-src', 46 | 'font-face-uri', 47 | 'font-face-format', 48 | 'font-face-name', 49 | 'missing-glyph', 50 | ]; 51 | 52 | export function createNgElementConstructor( 53 | appContext: NgElementApplicationContext, 54 | componentFactory: ComponentFactory): NgElementConstructorInternal { 55 | const selector = componentFactory.selector; 56 | 57 | if (!isPotentialCustomElementName(selector)) { 58 | throwError( 59 | `Using '${selector}' as a custom element name is not allowed. ` + 60 | 'See https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name for more info.'); 61 | } 62 | 63 | const inputs = componentFactory.inputs.map(({propName, templateName}) => ({ 64 | propName, 65 | attrName: camelToKebabCase(templateName), 66 | })); 67 | const outputs = 68 | componentFactory.outputs.map(({propName, templateName}) => ({ 69 | propName, 70 | // TODO(gkalpak): Verify this is what we want and document. 71 | eventName: templateName, 72 | })); 73 | 74 | // Note: According to the spec, this needs to be an ES2015 class 75 | // (i.e. not transpiled to an ES5 constructor function). 76 | // TODO(gkalpak): Document that if you are using ES5 sources you need to include a polyfill (e.g. 77 | // https://github.com/webcomponents/custom-elements/blob/32f043c3a/src/native-shim.js). 78 | class NgElementConstructorImpl extends NgElementImpl { 79 | static readonly is = selector; 80 | static readonly observedAttributes = inputs.map(input => input.attrName); 81 | static readonly onConnected = new EventEmitter>(); 82 | static readonly onDisconnected = new EventEmitter>(); 83 | 84 | static upgrade(host: HTMLElement, ignoreUpgraded = false): NgElementWithProps { 85 | const ngElement = new NgElementConstructorImpl(); 86 | 87 | ngElement.setHost(host); 88 | ngElement.connectedCallback(ignoreUpgraded); 89 | 90 | return ngElement as typeof ngElement & WithProperties

; 91 | } 92 | 93 | constructor() { 94 | super(appContext, componentFactory, inputs, outputs); 95 | 96 | const ngElement = this as this & WithProperties

; 97 | this.onConnected.subscribe(() => NgElementConstructorImpl.onConnected.emit(ngElement)); 98 | this.onDisconnected.subscribe(() => NgElementConstructorImpl.onDisconnected.emit(ngElement)); 99 | } 100 | } 101 | 102 | inputs.forEach(({propName}) => { 103 | Object.defineProperty(NgElementConstructorImpl.prototype, propName, { 104 | get: function(this: NgElementImpl) { return this.getInputValue(propName); }, 105 | set: function(this: NgElementImpl, newValue: any) { 106 | this.setInputValue(propName, newValue); 107 | }, 108 | configurable: true, 109 | enumerable: true, 110 | }); 111 | }); 112 | 113 | return NgElementConstructorImpl as typeof NgElementConstructorImpl & { 114 | new (): NgElementConstructorImpl&WithProperties

; 115 | }; 116 | } 117 | 118 | function createPcenRe() { 119 | // According to [the 120 | // spec](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name), 121 | // `pcenChar` is allowed to contain Unicode characters in the 10000-EFFFF range. But in order to 122 | // match this characters with a RegExp, we need the implementation to support the `u` flag. 123 | // On browsers that do not support it, valid PotentialCustomElementNames using characters in the 124 | // 10000-EFFFF range will still cause an error (but these characters are not expected to be used 125 | // in practice). 126 | let pcenChar = '-.0-9_a-z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF' + 127 | '\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF' + 128 | '\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; 129 | let flags = ''; 130 | 131 | if (RegExp.prototype.hasOwnProperty('unicode')) { 132 | pcenChar += '\\u{10000}-\\u{EFFFF}'; 133 | flags += 'u'; 134 | } 135 | 136 | return RegExp(`^[a-z][${pcenChar}]*-[${pcenChar}]*$`, flags); 137 | } 138 | 139 | function isPotentialCustomElementName(name: string): boolean { 140 | return PCEN_RE.test(name) && (PCEN_BLACKLIST.indexOf(name) === -1); 141 | } 142 | -------------------------------------------------------------------------------- /src/@angular/elements/src/ng-element.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {ApplicationRef, ComponentFactory, ComponentRef, EventEmitter, Injector, OnChanges, SimpleChange, SimpleChanges} from '@angular/core'; 10 | import {Subscription} from 'rxjs/Subscription'; 11 | 12 | import {extractProjectableNodes} from './extract-projectable-nodes'; 13 | import {NgElementApplicationContext} from './ng-element-application-context'; 14 | import {createCustomEvent, getComponentName, isFunction, scheduler, strictEquals, throwError} from './utils'; 15 | 16 | /** 17 | * TODO(gkalpak): Add docs. 18 | * @experimental 19 | */ 20 | export type NgElementWithProps = NgElement& {[property in keyof P]: P[property]}; 21 | 22 | /** 23 | * TODO(gkalpak): Add docs. 24 | * @experimental 25 | */ 26 | export interface NgElement extends HTMLElement { 27 | ngElement: NgElement|null; 28 | componentRef: ComponentRef|null; 29 | 30 | attributeChangedCallback( 31 | attrName: string, oldValue: string|null, newValue: string, namespace?: string): void; 32 | connectedCallback(): void; 33 | detach(): void; 34 | detectChanges(): void; 35 | disconnectedCallback(): void; 36 | getHost(): HTMLElement; 37 | markDirty(): void; 38 | } 39 | 40 | /** 41 | * Represents an `NgElement` input. 42 | * Similar to a `ComponentFactory` input (`{propName: string, templateName: string}`), 43 | * except that `attrName` is derived by kebab-casing `templateName`. 44 | */ 45 | export interface NgElementInput { 46 | propName: string; 47 | attrName: string; 48 | } 49 | 50 | /** 51 | * Represents an `NgElement` input. 52 | * Similar to a `ComponentFactory` output (`{propName: string, templateName: string}`), 53 | * except that `templateName` is renamed to `eventName`. 54 | */ 55 | export interface NgElementOutput { 56 | propName: string; 57 | eventName: string; 58 | } 59 | 60 | /** 61 | * An enum of possible lifecycle phases for `NgElement`s. 62 | */ 63 | const enum NgElementLifecyclePhase { 64 | // The element has been instantiated, but not connected. 65 | // (The associated component has not been created yet.) 66 | unconnected = 'unconnected', 67 | // The element has been instantiated and connected. 68 | // (The associated component has been created.) 69 | connected = 'connected', 70 | // The element has been instantiated, connected and then disconnected. 71 | // (The associated component has been created and then destroyed.) 72 | disconnected = 'disconnected', 73 | } 74 | 75 | interface NgElementConnected extends NgElementImpl { 76 | ngElement: NgElementConnected; 77 | componentRef: ComponentRef; 78 | } 79 | 80 | export abstract class NgElementImpl extends HTMLElement implements NgElement { 81 | private static DESTROY_DELAY = 10; 82 | ngElement: NgElement|null = null; 83 | componentRef: ComponentRef|null = null; 84 | onConnected = new EventEmitter(); 85 | onDisconnected = new EventEmitter(); 86 | 87 | private host = this as HTMLElement; 88 | private readonly componentName = getComponentName(this.componentFactory.componentType); 89 | private readonly initialInputValues = new Map(); 90 | private readonly uninitializedInputs = new Set(); 91 | private readonly outputSubscriptions = new Map(); 92 | private inputChanges: SimpleChanges|null = null; 93 | private implementsOnChanges = false; 94 | private changeDetectionScheduled = false; 95 | private lifecyclePhase: NgElementLifecyclePhase = NgElementLifecyclePhase.unconnected; 96 | private cancelDestruction: (() => void)|null = null; 97 | 98 | constructor( 99 | private appContext: NgElementApplicationContext, 100 | private componentFactory: ComponentFactory, private readonly inputs: NgElementInput[], 101 | private readonly outputs: NgElementOutput[]) { 102 | super(); 103 | } 104 | 105 | attributeChangedCallback( 106 | attrName: string, oldValue: string|null, newValue: string, namespace?: string): void { 107 | const input = this.inputs.find(input => input.attrName === attrName) !; 108 | 109 | if (input) { 110 | this.setInputValue(input.propName, newValue); 111 | } else { 112 | throwError( 113 | `Calling 'attributeChangedCallback()' with unknown attribute '${attrName}' ` + 114 | `on component '${this.componentName}' is not allowed.`); 115 | } 116 | } 117 | 118 | connectedCallback(ignoreUpgraded = false): void { 119 | this.assertNotInPhase(NgElementLifecyclePhase.disconnected, 'connectedCallback'); 120 | 121 | if (this.cancelDestruction !== null) { 122 | this.cancelDestruction(); 123 | this.cancelDestruction = null; 124 | } 125 | 126 | if (this.lifecyclePhase === NgElementLifecyclePhase.connected) { 127 | return; 128 | } 129 | 130 | const host = this.host as NgElement; 131 | 132 | if (host.ngElement) { 133 | if (ignoreUpgraded) { 134 | return; 135 | } 136 | 137 | const existingNgElement = (host as NgElementConnected).ngElement; 138 | const existingComponentName = getComponentName(existingNgElement.componentRef.componentType); 139 | 140 | throwError( 141 | `Upgrading '${this.host.nodeName}' element to component '${this.componentName}' is not allowed, ` + 142 | `because the element is already upgraded to component '${existingComponentName}'.`); 143 | } 144 | 145 | this.appContext.runInNgZone(() => { 146 | this.lifecyclePhase = NgElementLifecyclePhase.connected; 147 | const cThis = (this as any as NgElementConnected); 148 | 149 | const childInjector = Injector.create([], cThis.appContext.injector); 150 | const projectableNodes = 151 | extractProjectableNodes(cThis.host, cThis.componentFactory.ngContentSelectors); 152 | cThis.componentRef = 153 | cThis.componentFactory.create(childInjector, projectableNodes, cThis.host); 154 | cThis.implementsOnChanges = 155 | isFunction((cThis.componentRef.instance as any as OnChanges).ngOnChanges); 156 | 157 | cThis.initializeInputs(); 158 | cThis.initializeOutputs(); 159 | cThis.detectChanges(); 160 | 161 | cThis.appContext.applicationRef.attachView(cThis.componentRef.hostView); 162 | 163 | // Ensure `ngElement` is set on the host too (even for manually upgraded elements) 164 | // in order to be able to detect that the element has been been upgraded. 165 | cThis.ngElement = host.ngElement = cThis; 166 | 167 | cThis.onConnected.emit(); 168 | }); 169 | } 170 | 171 | detach(): void { this.disconnectedCallback(); } 172 | 173 | detectChanges(): void { 174 | if (this.lifecyclePhase === NgElementLifecyclePhase.disconnected) { 175 | return; 176 | } 177 | 178 | this.assertNotInPhase(NgElementLifecyclePhase.unconnected, 'detectChanges'); 179 | 180 | this.appContext.runInNgZone(() => { 181 | const cThis = this as any as NgElementConnected; 182 | 183 | cThis.changeDetectionScheduled = false; 184 | 185 | cThis.callNgOnChanges(); 186 | cThis.componentRef.changeDetectorRef.detectChanges(); 187 | }); 188 | } 189 | 190 | disconnectedCallback(): void { 191 | if (this.lifecyclePhase === NgElementLifecyclePhase.disconnected || 192 | this.cancelDestruction !== null) { 193 | return; 194 | } 195 | 196 | this.assertNotInPhase(NgElementLifecyclePhase.unconnected, 'disconnectedCallback'); 197 | 198 | const doDestroy = () => this.appContext.runInNgZone(() => this.destroy()); 199 | this.cancelDestruction = scheduler.schedule(doDestroy, NgElementImpl.DESTROY_DELAY); 200 | } 201 | 202 | getHost(): HTMLElement { return this.host; } 203 | 204 | getInputValue(propName: string): any { 205 | this.assertNotInPhase(NgElementLifecyclePhase.disconnected, 'getInputValue'); 206 | 207 | if (this.lifecyclePhase === NgElementLifecyclePhase.unconnected) { 208 | return this.initialInputValues.get(propName); 209 | } 210 | 211 | const cThis = this as any as NgElementConnected; 212 | 213 | return (cThis.componentRef.instance as any)[propName]; 214 | } 215 | 216 | markDirty(): void { 217 | if (!this.changeDetectionScheduled) { 218 | this.changeDetectionScheduled = true; 219 | scheduler.scheduleBeforeRender(() => this.detectChanges()); 220 | } 221 | } 222 | 223 | setHost(host: HTMLElement): void { 224 | this.assertNotInPhase(NgElementLifecyclePhase.connected, 'setHost'); 225 | this.assertNotInPhase(NgElementLifecyclePhase.disconnected, 'setHost'); 226 | 227 | this.host = host; 228 | } 229 | 230 | setInputValue(propName: string, newValue: any): void { 231 | this.assertNotInPhase(NgElementLifecyclePhase.disconnected, 'setInputValue'); 232 | 233 | if (this.lifecyclePhase === NgElementLifecyclePhase.unconnected) { 234 | this.initialInputValues.set(propName, newValue); 235 | return; 236 | } 237 | 238 | const cThis = this as any as NgElementConnected; 239 | 240 | if (!strictEquals(newValue, cThis.getInputValue(propName))) { 241 | cThis.recordInputChange(propName, newValue); 242 | (cThis.componentRef.instance as any)[propName] = newValue; 243 | cThis.markDirty(); 244 | } 245 | } 246 | 247 | private assertNotInPhase(phase: NgElementLifecyclePhase, caller: keyof this): void { 248 | if (this.lifecyclePhase === phase) { 249 | throwError( 250 | `Calling '${caller}()' on ${phase} component '${this.componentName}' is not allowed.`); 251 | } 252 | } 253 | 254 | private callNgOnChanges(this: NgElementConnected): void { 255 | if (this.implementsOnChanges && this.inputChanges !== null) { 256 | const inputChanges = this.inputChanges; 257 | this.inputChanges = null; 258 | (this.componentRef.instance as any as OnChanges).ngOnChanges(inputChanges); 259 | } 260 | } 261 | 262 | private destroy() { 263 | const cThis = this as any as NgElementConnected; 264 | 265 | cThis.componentRef.destroy(); 266 | cThis.outputs.forEach(output => cThis.unsubscribeFromOutput(output)); 267 | 268 | this.ngElement = (this.host as NgElement).ngElement = null; 269 | cThis.host.innerHTML = ''; 270 | 271 | cThis.lifecyclePhase = NgElementLifecyclePhase.disconnected; 272 | cThis.onDisconnected.emit(); 273 | } 274 | 275 | private dispatchCustomEvent(eventName: string, value: any): void { 276 | const event = createCustomEvent(this.host.ownerDocument, eventName, value); 277 | 278 | this.dispatchEvent(event); 279 | 280 | if (this.host !== this) { 281 | this.host.dispatchEvent(event); 282 | } 283 | } 284 | 285 | private initializeInputs(): void { 286 | this.inputs.forEach(({propName, attrName}) => { 287 | let initialValue; 288 | 289 | if (this.initialInputValues.has(propName)) { 290 | // The property has already been set (prior to initialization). 291 | // Update the component instance. 292 | initialValue = this.initialInputValues.get(propName); 293 | } else if (this.host.hasAttribute(attrName)) { 294 | // A matching attribute exists. 295 | // Update the component instance. 296 | initialValue = this.host.getAttribute(attrName); 297 | } else { 298 | // The property does not have an initial value. 299 | this.uninitializedInputs.add(propName); 300 | } 301 | 302 | if (!this.uninitializedInputs.has(propName)) { 303 | // The property does have an initial value. 304 | // Forward it to the component instance. 305 | this.setInputValue(propName, initialValue); 306 | } 307 | }); 308 | 309 | this.initialInputValues.clear(); 310 | } 311 | 312 | private initializeOutputs(this: NgElementConnected): void { 313 | this.outputs.forEach(output => this.subscribeToOutput(output)); 314 | } 315 | 316 | private recordInputChange(propName: string, currentValue: any): void { 317 | if (!this.implementsOnChanges) { 318 | // The component does not implement `OnChanges`. Ignore the change. 319 | return; 320 | } 321 | 322 | if (this.inputChanges === null) { 323 | this.inputChanges = {}; 324 | } 325 | 326 | const pendingChange = this.inputChanges[propName]; 327 | 328 | if (pendingChange) { 329 | pendingChange.currentValue = currentValue; 330 | return; 331 | } 332 | 333 | const isFirstChange = this.uninitializedInputs.has(propName); 334 | const previousValue = isFirstChange ? undefined : this.getInputValue(propName); 335 | this.inputChanges[propName] = new SimpleChange(previousValue, currentValue, isFirstChange); 336 | 337 | if (isFirstChange) { 338 | this.uninitializedInputs.delete(propName); 339 | } 340 | } 341 | 342 | private subscribeToOutput(this: NgElementConnected, output: NgElementOutput): void { 343 | const {propName, eventName} = output; 344 | const emitter = (this.componentRef.instance as any)[output.propName] as EventEmitter; 345 | 346 | if (!emitter) { 347 | throwError(`Missing emitter '${propName}' on component '${this.componentName}'.`); 348 | } 349 | 350 | this.unsubscribeFromOutput(output); 351 | 352 | const subscription = 353 | emitter.subscribe((value: any) => this.dispatchCustomEvent(eventName, value)); 354 | this.outputSubscriptions.set(propName, subscription); 355 | } 356 | 357 | private unsubscribeFromOutput({propName}: NgElementOutput): void { 358 | if (!this.outputSubscriptions.has(propName)) { 359 | return; 360 | } 361 | 362 | const subscription = this.outputSubscriptions.get(propName) !; 363 | 364 | this.outputSubscriptions.delete(propName); 365 | subscription.unsubscribe(); 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /src/@angular/elements/src/ng-elements.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {ComponentFactoryResolver, NgModuleRef, Type} from '@angular/core'; 10 | import {DOCUMENT} from '@angular/platform-browser'; 11 | 12 | import {NgElement} from './ng-element'; 13 | import {NgElementApplicationContext} from './ng-element-application-context'; 14 | import {NgElementConstructor, NgElementConstructorInternal, createNgElementConstructor} from './ng-element-constructor'; 15 | import {scheduler, throwError} from './utils'; 16 | 17 | /** 18 | * TODO(gkalpak): Add docs. 19 | * @experimental 20 | */ 21 | export class NgElements { 22 | private doc = this.moduleRef.injector.get(DOCUMENT); 23 | private definitions = new Map>(); 24 | private upgradedElements = new Set>(); 25 | private appContext = new NgElementApplicationContext(this.moduleRef.injector); 26 | private changeDetectionScheduled = false; 27 | 28 | constructor(public readonly moduleRef: NgModuleRef, customElementComponents: Type[]) { 29 | const resolver = moduleRef.componentFactoryResolver; 30 | customElementComponents.forEach( 31 | componentType => this.defineNgElement(this.appContext, resolver, componentType)); 32 | } 33 | 34 | detachAll(root: Element = this.doc.documentElement): void { 35 | const upgradedElements = Array.from(this.upgradedElements.values()); 36 | const elementsToDetach: NgElement[] = []; 37 | 38 | this.traverseTree(root, (node: HTMLElement) => { 39 | upgradedElements.some(ngElement => { 40 | if (ngElement.getHost() === node) { 41 | elementsToDetach.push(ngElement); 42 | return true; 43 | } 44 | return false; 45 | }); 46 | }); 47 | 48 | // Detach in reverse traversal order. 49 | this.appContext.runInNgZone( 50 | () => elementsToDetach.reverse().forEach(ngElement => ngElement.detach())); 51 | } 52 | 53 | detectChanges(): void { 54 | this.changeDetectionScheduled = false; 55 | this.appContext.runInNgZone( 56 | () => this.upgradedElements.forEach(ngElement => ngElement.detectChanges())); 57 | } 58 | 59 | forEach( 60 | cb: 61 | (def: NgElementConstructor, selector: string, 62 | map: Map>) => void): void { 63 | return this.definitions.forEach(cb); 64 | } 65 | 66 | get(selector: string): NgElementConstructor|undefined { 67 | return this.definitions.get(selector); 68 | } 69 | 70 | markDirty(): void { 71 | if (!this.changeDetectionScheduled) { 72 | this.changeDetectionScheduled = true; 73 | scheduler.scheduleBeforeRender(() => this.detectChanges()); 74 | } 75 | } 76 | 77 | register(customElements?: CustomElementRegistry): void { 78 | if (!customElements && (typeof window !== 'undefined')) { 79 | customElements = window.customElements; 80 | } 81 | 82 | if (!customElements) { 83 | throwError('Custom Elements are not supported in this environment.'); 84 | } 85 | 86 | this.definitions.forEach(def => customElements !.define(def.is, def)); 87 | } 88 | 89 | upgradeAll(root: Element = this.doc.documentElement): void { 90 | const definitions = Array.from(this.definitions.values()); 91 | 92 | this.appContext.runInNgZone(() => { 93 | this.traverseTree(root, (node: HTMLElement) => { 94 | const nodeName = node.nodeName.toLowerCase(); 95 | definitions.some(def => { 96 | if (def.is === nodeName) { 97 | // TODO(gkalpak): What happens if `node` contains more custom elements 98 | // (as projectable content)? 99 | def.upgrade(node, true); 100 | return true; 101 | } 102 | return false; 103 | }); 104 | }); 105 | }); 106 | } 107 | 108 | private defineNgElement( 109 | appContext: NgElementApplicationContext, resolver: ComponentFactoryResolver, 110 | componentType: Type): void { 111 | const componentFactory = resolver.resolveComponentFactory(componentType); 112 | const def = createNgElementConstructor(appContext, componentFactory); 113 | const selector = def.is; 114 | 115 | if (this.definitions.has(selector)) { 116 | throwError( 117 | `Defining an Angular custom element with selector '${selector}' is not allowed, ` + 118 | 'because one is already defined.'); 119 | } 120 | 121 | def.onConnected.subscribe((ngElement: NgElement) => this.upgradedElements.add(ngElement)); 122 | def.onDisconnected.subscribe( 123 | (ngElement: NgElement) => this.upgradedElements.delete(ngElement)); 124 | 125 | this.definitions.set(selector, def); 126 | } 127 | 128 | // TODO(gkalpak): Add support for traversing through `shadowRoot` 129 | // (as should happen according to the spec). 130 | // TODO(gkalpak): Investigate security implications (e.g. as seen in 131 | // https://github.com/angular/angular.js/pull/15699). 132 | private traverseTree(root: Element, cb: (node: HTMLElement) => void): void { 133 | let currentNode: Element|null = root; 134 | 135 | const getNextNonDescendant = (node: Element): Element | null => { 136 | let currNode: Element|null = node; 137 | let nextNode: Element|null = null; 138 | 139 | while (!nextNode && currNode && (currNode !== root)) { 140 | nextNode = currNode.nextElementSibling; 141 | currNode = currNode.parentElement; 142 | } 143 | 144 | return nextNode; 145 | }; 146 | 147 | while (currentNode) { 148 | if (currentNode instanceof HTMLElement) { 149 | cb(currentNode); 150 | } 151 | 152 | currentNode = currentNode.firstElementChild || getNextNonDescendant(currentNode); 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/@angular/elements/src/register-as-custom-elements.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {NgModuleFactory, NgModuleRef, PlatformRef, Type} from '@angular/core'; 10 | 11 | import {NgElements} from './ng-elements'; 12 | import {isFunction} from './utils'; 13 | 14 | /** 15 | * TODO(gkalpak): Add docs. 16 | * @experimental 17 | */ 18 | export function registerAsCustomElements( 19 | customElementComponents: Type[], platformRef: PlatformRef, 20 | moduleFactory: NgModuleFactory): Promise>; 21 | export function registerAsCustomElements( 22 | customElementComponents: Type[], 23 | bootstrapFn: () => Promise>): Promise>; 24 | export function registerAsCustomElements( 25 | customElementComponents: Type[], 26 | platformRefOrBootstrapFn: PlatformRef | (() => Promise>), 27 | moduleFactory?: NgModuleFactory): Promise> { 28 | const bootstrapFn = isFunction(platformRefOrBootstrapFn) ? 29 | platformRefOrBootstrapFn : 30 | () => platformRefOrBootstrapFn.bootstrapModuleFactory(moduleFactory !); 31 | 32 | return bootstrapFn().then(moduleRef => { 33 | const ngElements = new NgElements(moduleRef, customElementComponents); 34 | ngElements.register(); 35 | return moduleRef; 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /src/@angular/elements/src/utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {Type} from '@angular/core'; 10 | 11 | const elProto = Element.prototype as any; 12 | const matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || 13 | elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector; 14 | 15 | /** 16 | * Provide methods for scheduling the execution of a callback. 17 | */ 18 | export const scheduler = { 19 | /** 20 | * Schedule a callback to be called after some delay. 21 | */ 22 | schedule(cb: () => void, delay: number): () => 23 | void{const id = window.setTimeout(cb, delay); return () => window.clearTimeout(id);}, 24 | 25 | /** 26 | * Schedule a callback to be called before the next render. 27 | * (If `window.requestAnimationFrame()` is not available, use `scheduler.schedule()` instead.) 28 | */ 29 | scheduleBeforeRender(cb: () => void): () => void{ 30 | // TODO(gkalpak): Implement a better way of accessing `requestAnimationFrame()` 31 | // (e.g. accounting for vendor prefix, SSR-compatibility, etc). 32 | if (typeof window.requestAnimationFrame === 'undefined') { 33 | return scheduler.schedule(cb, 16); 34 | } const id = window.requestAnimationFrame(cb); 35 | return () => window.cancelAnimationFrame(id); 36 | }, 37 | }; 38 | 39 | /** 40 | * Convert a camelCased string to kebab-cased. 41 | */ 42 | export function camelToKebabCase(input: string): string { 43 | return input.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`); 44 | } 45 | 46 | /** 47 | * Create a `CustomEvent` (even on browsers where `CustomEvent` is not a constructor). 48 | */ 49 | export function createCustomEvent(doc: Document, name: string, detail: any): CustomEvent { 50 | const bubbles = false; 51 | const cancelable = false; 52 | 53 | // On IE9-11, `CustomEvent` is not a constructor. 54 | if (typeof CustomEvent !== 'function') { 55 | const event = doc.createEvent('CustomEvent'); 56 | event.initCustomEvent(name, bubbles, cancelable, detail); 57 | return event; 58 | } 59 | 60 | return new CustomEvent(name, {bubbles, cancelable, detail}); 61 | } 62 | 63 | /** 64 | * Return the name of the component or the first line of its stringified version. 65 | */ 66 | export function getComponentName(component: Type): string { 67 | return (component as any).overriddenName || component.name || 68 | component.toString().split('\n', 1)[0]; 69 | } 70 | 71 | /** 72 | * Check whether the input is an `Element`. 73 | */ 74 | export function isElement(node: Node): node is Element { 75 | return node.nodeType === Node.ELEMENT_NODE; 76 | } 77 | 78 | /** 79 | * Check whether the input is a function. 80 | */ 81 | export function isFunction(value: any): value is Function { 82 | return typeof value === 'function'; 83 | } 84 | 85 | /** 86 | * Convert a kebab-cased string to camelCased. 87 | */ 88 | export function kebabToCamelCase(input: string): string { 89 | return input.replace(/-([a-z\d])/g, (_, char) => char.toUpperCase()); 90 | } 91 | 92 | /** 93 | * Check whether an `Element` matches a CSS selector. 94 | */ 95 | export function matchesSelector(element: Element, selector: string): boolean { 96 | return matches.call(element, selector); 97 | } 98 | 99 | /** 100 | * Test two values for strict equality, accounting for the fact that `NaN !== NaN`. 101 | */ 102 | export function strictEquals(value1: any, value2: any): boolean { 103 | return value1 === value2 || (value1 !== value1 && value2 !== value2); 104 | } 105 | 106 | /** 107 | * Throw an error with the specified message. 108 | * (It provides a centralized place where it is easy to apply some change/behavior to all errors.) 109 | */ 110 | export function throwError(message: string): void { 111 | throw Error(message); 112 | } 113 | -------------------------------------------------------------------------------- /src/@angular/elements/src/version.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {Version} from '@angular/core'; 10 | 11 | /** 12 | * @experimental 13 | */ 14 | export const VERSION = new Version('0.0.0-PLACEHOLDER'); 15 | -------------------------------------------------------------------------------- /src/@angular/elements/tsconfig-build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig-build.json", 3 | 4 | "compilerOptions": { 5 | "baseUrl": ".", 6 | "rootDir": ".", 7 | "paths": { 8 | "@angular/common": ["../../dist/packages/common"], 9 | "@angular/core": ["../../dist/packages/core"], 10 | "@angular/platform-browser": ["../../dist/packages/platform-browser"] 11 | }, 12 | "outDir": "../../dist/packages/elements" 13 | }, 14 | 15 | "files": [ 16 | "public_api.ts", 17 | "../../node_modules/zone.js/dist/zone.js.d.ts" 18 | ], 19 | 20 | "angularCompilerOptions": { 21 | "annotateForClosureCompiler": true, 22 | "strictMetadataEmit": false, 23 | "skipTemplateCodegen": true, 24 | "flatModuleOutFile": "elements.js", 25 | "flatModuleId": "@angular/elements" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- 1 | :host { 2 | padding-top: 70px; 3 | display: block; 4 | } 5 | 6 | .spacer { 7 | flex: 1; 8 | } 9 | 10 | mat-toolbar { 11 | position: fixed; 12 | box-shadow: 0 3px 5px -1px rgba(0, 0, 0, 0.2), 0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12); 13 | z-index: 100; 14 | top: 0; 15 | } 16 | 17 | button.themeButton { 18 | min-width: 120px; 19 | } 20 | 21 | mat-card { 22 | max-width: 1000px; 23 | margin-left: auto; 24 | margin-right: auto; 25 | margin-top: 20px; 26 | position: relative; 27 | min-height: 300px; 28 | } 29 | 30 | .textCenter { 31 | text-align: center; 32 | } 33 | 34 | img { 35 | height: 40px; 36 | vertical-align: bottom; 37 | } 38 | 39 | li { 40 | line-height: 30px; 41 | } 42 | 43 | li > span { 44 | opacity: .6; 45 | } 46 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Angular Elements 5 | 6 | 7 | 11 | 12 |

13 |

14 | Angular Logo 16 | Web Components: How to create! 17 |

18 | 19 |
20 | 21 |

Info:

22 |

23 | This application creates web components using Angular Elements, which is not released yet, but it works pretty well, there 24 | is a branch in angular repository: 25 | labs/elements 29 |
30 |
We have three different web components here: 31 |

32 |
    33 |
  • app-like-button 34 | - just one simple component 35 |
  • 36 |
  • app-module-shell 37 | - shell for (minimal version, to be integrated in another systems) 38 |
  • 39 |
  • app-module-root 40 | - this is current page that you are viewing (a.k.a. bootstrap page) 41 |
  • 42 |
43 |
We are using routing also,with MockLocationStrategy to make it isolated from main router, when app-module-shell will be 44 | used in another application. 45 |
46 |
Also you can see how those web components can be used: 47 | https://angular-webcomponents-usage-sample.now.sh/ 51 |
52 | 53 |

Theme:

54 |

@angular/material/prebuilt-themes/indigo-pink.css

55 | 58 |
59 |
60 | 63 |
64 | 65 | 67 | 69 |

Loaded Page Content:

70 |
71 | 72 |
73 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { AppComponent } from './app.component'; 3 | describe('AppComponent', () => { 4 | beforeEach(async(() => { 5 | TestBed.configureTestingModule({ 6 | declarations: [ 7 | AppComponent 8 | ], 9 | }).compileComponents(); 10 | })); 11 | it('should create the app', async(() => { 12 | const fixture = TestBed.createComponent(AppComponent); 13 | const app = fixture.debugElement.componentInstance; 14 | expect(app).toBeTruthy(); 15 | })); 16 | it(`should have as title 'app'`, async(() => { 17 | const fixture = TestBed.createComponent(AppComponent); 18 | const app = fixture.debugElement.componentInstance; 19 | expect(app.title).toEqual('app'); 20 | })); 21 | it('should render title in a h1 tag', async(() => { 22 | const fixture = TestBed.createComponent(AppComponent); 23 | fixture.detectChanges(); 24 | const compiled = fixture.debugElement.nativeElement; 25 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!'); 26 | })); 27 | }); 28 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | @Component({ 5 | selector: 'app-module-root', 6 | templateUrl: './app.component.html', 7 | styleUrls: ['./app.component.css'] 8 | }) 9 | export class AppComponent implements OnInit { 10 | title = 'Angular Elements Demo'; 11 | 12 | constructor( 13 | private router: Router 14 | ) { } 15 | 16 | ngOnInit() { 17 | // first navigation not fired when loading in web component 18 | this.router.navigate(['/page1']); 19 | } 20 | 21 | openGithub() { 22 | window.open('https://github.com/playerx/angular-elements-sample'); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { LocationStrategy } from '@angular/common'; 4 | import { MockLocationStrategy } from '@angular/common/testing'; 5 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 6 | import { RouterModule } from '@angular/router'; 7 | 8 | import { MaterialModule } from './common/material.module'; 9 | import { AppComponent } from './app.component'; 10 | import { LikeButtonComponent } from './like-button/like-button.component'; 11 | import { Page1Component } from './page1/page1.component'; 12 | import { Page2Component } from './page2/page2.component'; 13 | import { routes } from 'app/routes'; 14 | import { ModuleShellComponent } from './module-shell/module-shell.component'; 15 | 16 | export const webComponents = [ 17 | ModuleShellComponent, 18 | Page1Component, 19 | Page2Component, 20 | LikeButtonComponent, 21 | AppComponent, 22 | ]; 23 | 24 | 25 | @NgModule({ 26 | declarations: [ 27 | ...webComponents, 28 | ], 29 | entryComponents: [ 30 | ...webComponents 31 | ], 32 | imports: [ 33 | BrowserModule, 34 | BrowserAnimationsModule, 35 | MaterialModule, 36 | RouterModule.forRoot(routes), 37 | ], 38 | providers: [ 39 | { provide: LocationStrategy, useClass: MockLocationStrategy } 40 | ], 41 | }) 42 | export class AppModule { 43 | ngDoBootstrap() { } 44 | } 45 | -------------------------------------------------------------------------------- /src/app/common/material.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { 3 | MatButtonModule, 4 | MatToolbarModule, 5 | MatCardModule, 6 | } from '@angular/material'; 7 | 8 | 9 | @NgModule({ 10 | exports: [ 11 | MatButtonModule, 12 | MatToolbarModule, 13 | MatCardModule 14 | ], 15 | }) 16 | export class MaterialModule { } 17 | -------------------------------------------------------------------------------- /src/app/like-button/like-button.component.html: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /src/app/like-button/like-button.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playerx/angular-elements-sample/1be4ca3d835090cfdf93251ca7cda7342e6a73f7/src/app/like-button/like-button.component.scss -------------------------------------------------------------------------------- /src/app/like-button/like-button.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { LikeButtonComponent } from './like-button.component'; 4 | 5 | describe('LikeButtonComponent', () => { 6 | let component: LikeButtonComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ LikeButtonComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LikeButtonComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/like-button/like-button.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; 2 | import { } from 'selenium-webdriver'; 3 | 4 | @Component({ 5 | selector: 'app-like-button', 6 | templateUrl: './like-button.component.html', 7 | styleUrls: ['./like-button.component.scss'] 8 | }) 9 | export class LikeButtonComponent implements OnInit { 10 | 11 | @Input() 12 | likes: number; 13 | 14 | @Output() 15 | liked = new EventEmitter(); 16 | 17 | constructor() { } 18 | 19 | ngOnInit() { 20 | } 21 | 22 | onClick() { 23 | this.likes++; 24 | this.liked.emit(this.likes); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/app/module-shell/module-shell.component.html: -------------------------------------------------------------------------------- 1 |
2 | 4 | 6 |

Loaded Page Content:

7 | 8 | Hello from another angular app! 9 | 10 |
11 | 12 |
13 | -------------------------------------------------------------------------------- /src/app/module-shell/module-shell.component.scss: -------------------------------------------------------------------------------- 1 | main { 2 | min-height: 400px; 3 | display: block; 4 | } 5 | -------------------------------------------------------------------------------- /src/app/module-shell/module-shell.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ModuleShellComponent } from './module-shell.component'; 4 | 5 | describe('ModuleShellComponent', () => { 6 | let component: ModuleShellComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ModuleShellComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ModuleShellComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/module-shell/module-shell.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, ViewEncapsulation } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | @Component({ 5 | selector: 'app-module-shell', 6 | templateUrl: './module-shell.component.html', 7 | styleUrls: ['./module-shell.component.scss'], 8 | }) 9 | export class ModuleShellComponent implements OnInit { 10 | 11 | constructor( 12 | private router: Router 13 | ) { } 14 | 15 | ngOnInit() { 16 | // first navigation not fired when loading in web component 17 | this.router.navigate(['/page1']); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/app/page1/page1.component.html: -------------------------------------------------------------------------------- 1 |

2 | page1 works! 3 |

4 | 6 | -------------------------------------------------------------------------------- /src/app/page1/page1.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playerx/angular-elements-sample/1be4ca3d835090cfdf93251ca7cda7342e6a73f7/src/app/page1/page1.component.scss -------------------------------------------------------------------------------- /src/app/page1/page1.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { Page1Component } from './page1.component'; 4 | 5 | describe('Page1Component', () => { 6 | let component: Page1Component; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ Page1Component ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(Page1Component); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/page1/page1.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-page1', 5 | templateUrl: './page1.component.html', 6 | styleUrls: ['./page1.component.scss'] 7 | }) 8 | export class Page1Component implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/app/page2/page2.component.html: -------------------------------------------------------------------------------- 1 |

2 | page2 works! 3 |

4 | 5 | 6 | 7 | 11 | -------------------------------------------------------------------------------- /src/app/page2/page2.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playerx/angular-elements-sample/1be4ca3d835090cfdf93251ca7cda7342e6a73f7/src/app/page2/page2.component.scss -------------------------------------------------------------------------------- /src/app/page2/page2.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { Page2Component } from './page2.component'; 4 | 5 | describe('Page2Component', () => { 6 | let component: Page2Component; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ Page2Component ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(Page2Component); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/page2/page2.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-page2', 5 | templateUrl: './page2.component.html', 6 | styleUrls: ['./page2.component.scss'] 7 | }) 8 | export class Page2Component implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/app/routes.ts: -------------------------------------------------------------------------------- 1 | import { Routes } from '@angular/router'; 2 | import { Page1Component } from 'app/page1/page1.component'; 3 | import { Page2Component } from 'app/page2/page2.component'; 4 | 5 | 6 | export const routes: Routes = [ 7 | { path: '', redirectTo: 'page1', pathMatch: 'full' }, 8 | { path: 'page1', component: Page1Component }, 9 | { path: 'page2', component: Page2Component }, 10 | { path: '**', redirectTo: 'page1' } 11 | ]; 12 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playerx/angular-elements-sample/1be4ca3d835090cfdf93251ca7cda7342e6a73f7/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playerx/angular-elements-sample/1be4ca3d835090cfdf93251ca7cda7342e6a73f7/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | AngularElementsSample 7 | 8 | 9 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode, destroyPlatform, Type, NgModuleFactory, CompilerFactory } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | import { registerAsCustomElements } from '@angular/elements'; 4 | 5 | import { AppModule, webComponents } from './app/app.module'; 6 | import { environment } from './environments/environment'; 7 | import { platformBrowser } from '@angular/platform-browser'; 8 | 9 | if (environment.production) { 10 | enableProdMode(); 11 | } 12 | 13 | destroyPlatform(); 14 | 15 | const bootstrapFn = () => platformBrowserDynamic().bootstrapModule(AppModule); 16 | registerAsCustomElements(webComponents, bootstrapFn) 17 | .then(() => console.log('Web Components are ready!')) 18 | .catch(err => console.log(err)); 19 | -------------------------------------------------------------------------------- /src/now.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-elements-sample", 3 | "alias": "angular-elements-sample", 4 | "type": "static" 5 | } 6 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following for the Reflect API. */ 41 | // import 'core-js/es6/reflect'; 42 | 43 | 44 | /** Evergreen browsers require these. **/ 45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. 46 | import 'core-js/es7/reflect'; 47 | 48 | 49 | /** 50 | * Required to support Web Animations `@angular/platform-browser/animations`. 51 | * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation 52 | **/ 53 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 54 | 55 | 56 | 57 | /*************************************************************************************************** 58 | * Zone JS is required by default for Angular itself. 59 | */ 60 | import 'zone.js/dist/zone'; // Included with Angular CLI. 61 | 62 | 63 | 64 | /*************************************************************************************************** 65 | * APPLICATION IMPORTS 66 | */ 67 | import '@webcomponents/custom-elements/src/native-shim'; 68 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | @import "~@angular/material/prebuilt-themes/indigo-pink.css"; 2 | 3 | @import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"); 4 | 5 | html, body { 6 | margin: 0; 7 | font-family: 'Roboto', sans-serif; 8 | background: #f3f3f3; 9 | } 10 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare const __karma__: any; 17 | declare const require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "baseUrl": "./", 6 | "module": "es2015", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts" 15 | ], 16 | "include": [ 17 | "**/*.spec.ts", 18 | "**/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "baseUrl": "src", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "moduleResolution": "node", 9 | "emitDecoratorMetadata": true, 10 | "experimentalDecorators": true, 11 | "target": "es5", 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "lib": [ 16 | "es2017", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs", 22 | "rxjs/Rx" 23 | ], 24 | "import-spacing": true, 25 | "indent": [ 26 | true, 27 | "spaces" 28 | ], 29 | "interface-over-type-literal": true, 30 | "label-position": true, 31 | "max-line-length": [ 32 | true, 33 | 140 34 | ], 35 | "member-access": false, 36 | "member-ordering": [ 37 | true, 38 | { 39 | "order": [ 40 | "static-field", 41 | "instance-field", 42 | "static-method", 43 | "instance-method" 44 | ] 45 | } 46 | ], 47 | "no-arg": true, 48 | "no-bitwise": true, 49 | "no-console": [ 50 | true, 51 | "debug", 52 | "info", 53 | "time", 54 | "timeEnd", 55 | "trace" 56 | ], 57 | "no-construct": true, 58 | "no-debugger": true, 59 | "no-duplicate-super": true, 60 | "no-empty": false, 61 | "no-empty-interface": true, 62 | "no-eval": true, 63 | "no-inferrable-types": [ 64 | true, 65 | "ignore-params" 66 | ], 67 | "no-misused-new": true, 68 | "no-non-null-assertion": true, 69 | "no-shadowed-variable": true, 70 | "no-string-literal": false, 71 | "no-string-throw": true, 72 | "no-switch-case-fall-through": true, 73 | "no-trailing-whitespace": true, 74 | "no-unnecessary-initializer": true, 75 | "no-unused-expression": true, 76 | "no-use-before-declare": true, 77 | "no-var-keyword": true, 78 | "object-literal-sort-keys": false, 79 | "one-line": [ 80 | true, 81 | "check-open-brace", 82 | "check-catch", 83 | "check-else", 84 | "check-whitespace" 85 | ], 86 | "prefer-const": true, 87 | "quotemark": [ 88 | true, 89 | "single" 90 | ], 91 | "radix": true, 92 | "semicolon": [ 93 | true, 94 | "always" 95 | ], 96 | "triple-equals": [ 97 | true, 98 | "allow-null-check" 99 | ], 100 | "typedef-whitespace": [ 101 | true, 102 | { 103 | "call-signature": "nospace", 104 | "index-signature": "nospace", 105 | "parameter": "nospace", 106 | "property-declaration": "nospace", 107 | "variable-declaration": "nospace" 108 | } 109 | ], 110 | "typeof-compare": true, 111 | "unified-signatures": true, 112 | "variable-name": false, 113 | "whitespace": [ 114 | true, 115 | "check-branch", 116 | "check-decl", 117 | "check-operator", 118 | "check-separator", 119 | "check-type" 120 | ], 121 | "directive-selector": [ 122 | true, 123 | "attribute", 124 | "app", 125 | "camelCase" 126 | ], 127 | "component-selector": [ 128 | true, 129 | "element", 130 | "app", 131 | "kebab-case" 132 | ], 133 | "no-output-on-prefix": true, 134 | "use-input-property-decorator": true, 135 | "use-output-property-decorator": true, 136 | "use-host-property-decorator": true, 137 | "no-input-rename": true, 138 | "no-output-rename": true, 139 | "use-life-cycle-interface": true, 140 | "use-pipe-transform-interface": true, 141 | "component-class-suffix": true, 142 | "directive-class-suffix": true 143 | } 144 | } 145 | --------------------------------------------------------------------------------