Advertisement
Guest User

Untitled

a guest
Sep 10th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. import { Component, OnInit } from '@angular/core';
  2. import { REACTIVE_FORM_DIRECTIVES, FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
  3.  
  4. @Component({
  5. selector: 'my-app',
  6. templateUrl: 'app/templates/app.component.html',
  7. directives: [REACTIVE_FORM_DIRECTIVES],
  8. providers: [FormBuilder]
  9. })
  10. export class AppComponent {
  11. loginForm: FormGroup;
  12.  
  13. username: FormControl;
  14. password: FormControl;
  15.  
  16. constructor(builder: FormBuilder) {
  17. this.username = new FormControl('', [
  18. Validators.required,
  19. Validators.maxLength(3)
  20. ]);
  21. this.password = new FormControl('', Validators.required);
  22.  
  23. this.loginForm = builder.group({
  24. username: this.username,
  25. password: this.password
  26. });
  27. }
  28.  
  29. onSubmit() {}
  30. }
  31.  
  32. import { Input, OnInit, Directive, ElementRef, Renderer } from '@angular/core';
  33. import { FormControl } from '@angular/forms';
  34.  
  35. @Directive({
  36. selector: '[hide-valid]'
  37. })
  38. export class HideValidDirective {
  39. valid: Boolean;
  40.  
  41. @Input() set isValid(property: FormControl) {
  42. this.valid = property.untouched || property.valid;
  43. this.set();
  44. }
  45.  
  46. constructor(
  47. private el: ElementRef,
  48. private renderer: Renderer) {
  49. }
  50.  
  51. set() {
  52. if (this.valid) {
  53. this.renderer.setElementStyle(this.el.nativeElement,
  54. 'display', 'none');
  55. }
  56. }
  57. }
  58.  
  59. <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
  60. <label for="username">username</label>
  61. <input type="text" name="username" id="username" [formControl]="username">
  62. <div [hidden]="username.valid || username.untouched">
  63. <span *ngIf="username.hasError('required')">Field is required</span>
  64. <span *ngIf="username.hasError('maxlength')">Field is limited to 3 characters.</span>
  65. </div>
  66. <button type="submit">log in</button>
  67. </form>
  68.  
  69. <div [hidden]="username.valid || username.untouched">
  70. <span *ngIf="username.hasError('required')">Field is required</span>
  71. <span *ngIf="username.hasError('maxlength')">Field is limited to 3 characters.</span>
  72. </div>
  73.  
  74. <div hide-valid isValid="{{ username }}">
  75. <span *ngIf="username.hasError('required')">Field is required</span>
  76. <span *ngIf="username.hasError('maxlength')">Field is limited to 3 characters.</span>
  77. </div>
  78.  
  79. <div hide-valid [isValid]="username">
  80.  
  81. <div [isValid]="username">
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement