<!DOCTYPE html>
<html>
<head>
<title>Angular 2+ Custom Form Controls</title>
<script src="https://unpkg.com/core-js/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
<script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
<style>
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
}
</style>
</head>
<body>
<app-root>Loading...</app-root>
</body>
</html>
import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
myForm: FormGroup
value = false;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
mySwitch: [true]
});
}
submit() {
alert(`Value: ${this.myForm.controls.mySwitch.value}`);
console.log(`Value: ${this.myForm.controls.mySwitch.value}`);
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { SwitchComponent } from './switch.component';
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
FormsModule
],
declarations: [
AppComponent,
SwitchComponent
],
providers: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
<h1>Angular Custom Form Control</h1>
<br />
<h3>NgModel</h3>
<app-switch [(ngModel)]="value" [label]="'My Switch'"></app-switch><br />
<strong>Value:</strong> {{value}}
<br /><br />
<hr />
<br />
<h3>Reactive Forms</h3>
<form [formGroup]="myForm" (ngSubmit)="submit()">
<app-switch formControlName="mySwitch" [label]="'My Switch'"></app-switch>
<button>Submit</button>
</form>
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
/**
* WEB ANGULAR VERSION
* (based on systemjs.config.js in angular.io)
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
// DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
transpiler: 'ts',
typescriptOptions: {
// Copy of compiler options in standard tsconfig.json
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
},
meta: {
'typescript': {
"exports": "ts"
}
},
paths: {
// paths serve as alias
'npm:': 'https://unpkg.com/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
// angular bundles
'@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
'@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs@5.5.2',
'rxjs/operators': 'npm:rxjs@5.5.2/operators/index.js',
'tslib': 'npm:tslib/tslib.js',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api@0.4/bundles/in-memory-web-api.umd.js',
'ts': 'npm:plugin-typescript@5.2.7/lib/plugin.js',
'typescript': 'npm:typescript@2.4.2/lib/typescript.js',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts',
meta: {
'./*.ts': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
import { Component, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-switch',
templateUrl: 'app/switch.component.html',
styleUrls: ['app/switch.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SwitchComponent),
multi: true
}
]
})
export class SwitchComponent implements ControlValueAccessor {
@Input() label = 'switch';
@Input('value') _value = false;
onChange: any = () => { };
onTouched: any = () => { };
get value() {
return this._value;
}
set value(val) {
this._value = val;
this.onChange(val);
this.onTouched();
}
constructor() { }
registerOnChange(fn) {
this.onChange = fn;
}
writeValue(value) {
console.log(value);
if (value) {
this.value = value;
}
}
registerOnTouched(fn) {
this.onTouched = fn;
}
switch() {
this.value = !this.value;
}
}
<div (click)="switch()" class="switch" [ngClass]="{ 'checked': value }" [attr.title]="label">
<input type="checkbox" class="switch-input" [value]="value" [attr.checked]="value" [attr.aria-label]="label">
<span class="switch-label" data-on="On" data-off="Off"></span>
<span class="switch-handle"></span>
</div>
.switch {
position: relative;
display: inline-block;
vertical-align: top;
width: 80px;
height: 30px;
padding: 3px;
background-color: none;
cursor: pointer;
overflow: visible;
}
.switch-input {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
.switch-label {
position: relative;
display: block;
height: inherit;
font-size: 16px;
font-weight: normal;
text-transform: uppercase;
background: #ccc;
border-radius: 4px;
transition: 0.15s ease-out;
transition-property: opacity background;
color: #2d2d2d;
}
.switch-label::before, .switch-label::after {
position: absolute;
top: 50%;
margin-top: -.5em;
line-height: 1;
transition: inherit;
}
.switch-label::before {
content: attr(data-off);
right: 11px;
color: #fff;
}
.switch-label::after {
content: attr(data-on);
left: 11px;
color: #fff;
opacity: 0;
}
.switch-handle {
position: absolute;
top: 9px;
left: 12px;
width: 18px;
height: 18px;
background: #fff;
border-radius: 10px;
box-shadow: 1px 1px 5px #2d2d2d;
transition: left 0.15s ease-out;
}
.checked .switch-label {
background: #4CAF50;
box-shadow: inset 0 1px 2px rgba(255, 255, 255, 0.5), inset 0 0 3px rgba(0, 0, 0, 0.15);
}
.checked .switch-label::before {
opacity: 0;
}
.checked .switch-label::after {
opacity: 1;
}
.checked .switch-handle {
left: 50px;
box-shadow: -1px 1px 5px rgba(45, 45, 45, 0.41);
}
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
module.exports.translate = function(load){
if (load.source.indexOf('moduleId') != -1) return load;
var url = document.createElement('a');
url.href = load.address;
var basePathParts = url.pathname.split('/');
basePathParts.pop();
var basePath = basePathParts.join('/');
var baseHref = document.createElement('a');
baseHref.href = this.baseURL;
baseHref = baseHref.pathname;
if (!baseHref.startsWith('/base/')) { // it is not karma
basePath = basePath.replace(baseHref, '');
}
load.source = load.source
.replace(templateUrlRegex, function(match, quote, url){
var resolvedUrl = url;
if (url.startsWith('.')) {
resolvedUrl = basePath + url.substr(1);
}
return 'templateUrl: "' + resolvedUrl + '"';
})
.replace(stylesRegex, function(match, relativeUrls) {
var urls = [];
while ((match = stringRegex.exec(relativeUrls)) !== null) {
if (match[2].startsWith('.')) {
urls.push('"' + basePath + match[2].substr(1) + '"');
} else {
urls.push('"' + match[2] + '"');
}
}
return "styleUrls: [" + urls.join(', ') + "]";
});
return load;
};