import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core'
import {
AbstractControl,
FormBuilder,
FormControl,
FormGroup,
Validators
} from '@angular/forms'
import {AlternativeValidationDirective} from 'angular-alternative-validation'
import {IAlternativeValidationConfig} from 'angular-alternative-validation/struct/alternative-validation-config'
@Component({
selector: 'my-app',
template: `
<h1>Basic Usage</h1>
<div class="row">
<div class="col-sm-12">
<form [formGroup]="basicFormGroup" class="card">
<div class="card-header">
The singer survey
</div>
<div class="card-block">
<div
class="form-group {{altInput.touched?'has-'+getControlFeedbackName(altInput, aV):''}}">
<label class="form-control-label">Female Singer
<small>(shows a demo uscase for validating and hinting form inputs)</small>
</label>
<input type="text" autocomplete="false"
class="form-control {{altInput.touched?'form-control-'+getControlFeedbackName(altInput, aV):''}}"
name="alt"
formControlName="alt"
[alternativeValidation]="avNameConfig"
#aV="alternativeValidation">
<small *ngIf="altInput.hasError('required') && altInput.touched"
class="form-control-feedback">
Input required
</small>
<small *ngIf="altInput.hasError('minlength') && altInput.touched"
class="form-control-feedback">
A minimum length of 3 is required
</small>
<small
*ngIf="!altInput.errors && aV.hasError('validName') && aV.touched"
class="form-control-feedback">
This is maybe not a name of a female singer. Try names like:
{{aV.getError('validName').validNames}}
</small>
<small *ngIf="altInput.valid && aV.valid && aV.touched"
class="form-control-feedback">
Good choice! :-)
</small>
<small *ngIf="aV.untouched" class="form-text text-muted">
Please enter a female singer that pops up first in your mind.
</small>
</div>
</div>
<div class="card-footer">
<button class="btn btn-primary" [disabled]="basicFormGroup.invalid"
type="submit">Save
</button>
<button class="btn btn-secondary" type="reset">Reset <small>native</small></button>
<button class="btn btn-secondary" type="button"
(click)="resetWithValue('Nei')">Reset <small>via code</small>
</button>
<button class="btn btn-secondary" type="button" (click)="toggleDisabled(altInput)">{{altInput.disabled?'Enabled':'Disable'}}</button>
<input type="text" autocomplete="false"
class="form-control pull-right col-4"
name="any-other-focus"
placeholder="Any Other Focus">
</div>
</form>
<br>
<div class="row">
<div class="col-6">
<control-state [control]="altInput">
Angular control states
</control-state>
</div>
<div class="col-6">
<control-state [control]="aV" [errorColor]="'warning'">
Alternative control states
</control-state>
</div>
</div>
</div>
</div>
`
})export class AppComponent implements OnInit, AfterViewInit {
basicFormGroup: FormGroup;
nativeInput: FormControl;
basicInput: FormControl;
cfnInput: FormControl;
altInput: FormControl;
avNameConfig: IAlternativeValidationConfig;
@ViewChild(AlternativeValidationDirective)
ref
constructor(private fb: FormBuilder) {
this.basicFormGroup = this.fb.group(
{
alt: ['initial', [Validators.required, Validators.minLength(3)]]
}
);
this.avNameConfig = {
validator: [
{name: 'validName'}
]
};
}
ngOnInit() {
this.altInput = this.basicFormGroup.get('alt') as FormControl
}
ngAfterViewInit() {
console.log('Reference to the directive', this.ref);
}
getControlFeedbackName(formControl: AbstractControl, altControl: AbstractControl): string {
if (formControl.disabled) {
return '';
}
if (formControl.invalid) {
return 'danger';
} else if (altControl.invalid) {
return 'warning';
} else {
return 'success';
}
}
toggleDisabled(control: AbstractControl) {
if (!control.disabled) {
control.disable();
} else {
control.enable();
}
}
resetWithValue(value) {
this.basicFormGroup.reset({
alt: 'reset'
})
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule,NG_VALIDATORS } from '@angular/forms';
import { AppComponent } from './app.component';
import { ControlStateComponent } from './control-state/control-state.component';
import { AlternativeValidationModule } from 'angular-alternative-validation';
import {validName} from './validators/valid-name'
@NgModule({
imports: [
BrowserModule,
AlternativeValidationModule.forRoot(),
],
declarations: [
AppComponent,
ControlStateComponent
],
providers: [
{provide: NG_VALIDATORS, useValue: validName, multi: true}
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
/*
Copyright 2017 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
*/
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
/*
Copyright 2017 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
*/
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
h2, h3 {
color: #444;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}
body {
margin: 2em;
}
body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
a {
cursor: pointer;
cursor: hand;
}
button {
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #aaa;
cursor: auto;
}
/* Navigation link styles */
nav a {
padding: 5px 10px;
text-decoration: none;
margin-right: 10px;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}
/* everywhere else */
* {
font-family: Arial, Helvetica, sans-serif;
}
/*
Copyright 2017 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
*/
<!DOCTYPE html>
<html>
<head>
<title>Angular Tour of Heroes</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<!-- Polyfills -->
<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('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
<!--
Copyright 2017 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
-->
/**
* 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/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.0.1',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ts': 'npm:plugin-typescript@5.2.7/lib/plugin.js',
'typescript': 'npm:typescript@2.3.2/lib/typescript.js',
'angular-alternative-validation': 'npm:angular-alternative-validation'
},
// 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
*/
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;
};
import {Component, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core'
import {FormControl} from '@angular/forms'
@Component({
selector: 'control-state',
styles: [`
ul {
list-style: none;
margin-bottom:0;
}
`],
template: `<div class="card">
<div class="card-header">
<h4>
<ng-content></ng-content>
</h4>
</div>
<ul *ngIf="control.errors"
class="card-block {{'bg-'+ errorColor}}">
<li *ngFor="let error of getErrors()" class="text-white">
<b>{{error.name}}</b>
</li>
</ul>
<div class="card-block">
<div class="row">
<div class="col-3"><b>value</b></div>
<div
class="col-9 text-primary">
<b>{{control.value}}</b>
</div>
<div class="col-3"><b>valid</b></div>
<div
class="col-3 {{control.valid?'text-success':'text-danger'}}">
{{control.valid }}
</div>
<div class="col-3"><b>invalid</b></div>
<div
class="col-3 {{control.invalid?'text-success':'text-danger'}}">
{{control.invalid }}
</div>
<div class="col-3"><b>status</b></div>
<div class="col-3" [ngClass]="{
'text-success': control.status==='VALID',
'text-danger': control.status==='INVALID',
'text-info': control.status==='PENDING'
}">{{control.status}}
</div>
<div class="col-3"><b>pending</b></div>
<div
class="col-3 {{control.pending?'text-success':'text-danger'}}">
{{control.pending}}
</div>
<div class="col-3"><b>pristine</b></div>
<div
class="col-3 {{control.pristine?'text-success':'text-danger'}}">
{{control.pristine}}
</div>
<div class="col-3"><b>dirty</b></div>
<div
class="col-3 {{control.dirty?'text-success':'text-danger'}}">
{{control.dirty}}
</div>
<div class="col-3"><b>touched</b></div>
<div
class="col-3 {{control.touched?'text-success':'text-danger'}}">
{{control.touched}}
</div>
<div class="col-3"><b>untouched</b></div>
<div
class="col-3 {{control.untouched?'text-success':'text-danger'}}">
{{control.untouched}}
</div>
<div class="col-3"><b>focus</b></div>
<div
class="col-3 {{control.focus?'text-success':'text-danger'}}">
{{control.focus}}
</div>
<div class="col-3"><b>disabled</b></div>
<div
class="col-3 {{control.disabled?'text-success':'text-danger'}}">
{{control.disabled}}
</div>
<div class="col-12"><b>errors</b></div>
<div
class="col-12 text-danger">
<pre>{{control.errors | json}}</pre>
</div>
</div>
</div>
</div>
`
})
export class ControlStateComponent implements OnChanges, OnInit {
@Input()
control: FormControl;
@Input()
errorColor = 'danger';
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
if ('errorColor' in changes) {
this.errorColor = changes.errorColor.currentValue || 'danger'
}
}
ngOnInit() {
}
getErrors(): any[] {
return Object.keys(this.control.errors)
.map((key) => {
return {
name: key,
value: this.control.errors[key]
}
})
}
}
import {AbstractControl, ValidationErrors} from '@angular/forms'
export function validName(c: AbstractControl): ValidationErrors | null {
const validNames = ['Aretha', 'Ella', 'Etta', 'Nina'];
const isValid = validNames
.map(n => c.value && c.value.indexOf(n) !== -1)
.filter(v => v)
.reduce((prev, curr) => true, false);
if (!isValid) {
return {
validName: {
valid: true,
validNames
}
}
}
return null
}