├── .editorconfig ├── .gitignore ├── README.md ├── angular.json ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.e2e.json ├── package-lock.json ├── package.json ├── src ├── app │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.dependencies.ts │ ├── app.module.ts │ ├── components │ │ ├── customer-details │ │ │ ├── customer-details.component.html │ │ │ ├── customer-details.component.scss │ │ │ └── customer-details.component.ts │ │ ├── navbar │ │ │ ├── navbar.component.html │ │ │ └── navbar.component.ts │ │ ├── pizza-list │ │ │ ├── pizza-list.component.html │ │ │ ├── pizza-list.component.scss │ │ │ └── pizza-list.component.ts │ │ ├── pizza-size-picker │ │ │ ├── pizza-size-picker.component.html │ │ │ ├── pizza-size-picker.component.scss │ │ │ └── pizza-size-picker.component.ts │ │ └── selected-pizza-viewer │ │ │ ├── selected-pizza-viewer.component.html │ │ │ ├── selected-pizza-viewer.component.scss │ │ │ └── selected-pizza-viewer.component.ts │ └── containers │ │ └── pizza-form-container │ │ ├── pizza-form-container.component.html │ │ ├── pizza-form-container.component.scss │ │ ├── pizza-form-container.component.ts │ │ └── services │ │ ├── demo-pizza-item.ts │ │ ├── pizza-form-validators.service.spec.ts │ │ ├── pizza-form-validators.service.ts │ │ ├── pizza-form.interface.ts │ │ ├── pizza-form.service.spec.ts │ │ ├── pizza-form.service.ts │ │ ├── pizza-loader.service.spec.ts │ │ └── pizza-loader.service.ts ├── assets │ └── .gitkeep ├── browserslist ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── karma.conf.js ├── main.ts ├── polyfills.ts ├── styles.scss ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── tslint.json ├── tsconfig.json └── tslint.json /.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 | yarn-error.log 34 | testem.log 35 | /typings 36 | 37 | # System Files 38 | .DS_Store 39 | Thumbs.db 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AngularFormsExample 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.1.3. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular-forms-example": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": {}, 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "outputPath": "dist/angular-forms-example", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": "src/polyfills.ts", 20 | "tsConfig": "src/tsconfig.app.json", 21 | "assets": [ 22 | "src/favicon.ico", 23 | "src/assets" 24 | ], 25 | "styles": [ 26 | { 27 | "input": "node_modules/@angular/material/prebuilt-themes/indigo-pink.css" 28 | }, 29 | "src/styles.scss" 30 | ], 31 | "scripts": [] 32 | }, 33 | "configurations": { 34 | "production": { 35 | "fileReplacements": [ 36 | { 37 | "replace": "src/environments/environment.ts", 38 | "with": "src/environments/environment.prod.ts" 39 | } 40 | ], 41 | "optimization": true, 42 | "outputHashing": "all", 43 | "sourceMap": false, 44 | "extractCss": true, 45 | "namedChunks": false, 46 | "aot": true, 47 | "extractLicenses": true, 48 | "vendorChunk": false, 49 | "buildOptimizer": true 50 | } 51 | } 52 | }, 53 | "serve": { 54 | "builder": "@angular-devkit/build-angular:dev-server", 55 | "options": { 56 | "browserTarget": "angular-forms-example:build" 57 | }, 58 | "configurations": { 59 | "production": { 60 | "browserTarget": "angular-forms-example:build:production" 61 | } 62 | } 63 | }, 64 | "extract-i18n": { 65 | "builder": "@angular-devkit/build-angular:extract-i18n", 66 | "options": { 67 | "browserTarget": "angular-forms-example:build" 68 | } 69 | }, 70 | "test": { 71 | "builder": "@angular-devkit/build-angular:karma", 72 | "options": { 73 | "main": "src/test.ts", 74 | "polyfills": "src/polyfills.ts", 75 | "tsConfig": "src/tsconfig.spec.json", 76 | "karmaConfig": "src/karma.conf.js", 77 | "styles": [ 78 | { 79 | "input": "node_modules/@angular/material/prebuilt-themes/indigo-pink.css" 80 | }, 81 | "src/styles.scss" 82 | ], 83 | "scripts": [], 84 | "assets": [ 85 | "src/favicon.ico", 86 | "src/assets" 87 | ] 88 | } 89 | }, 90 | "lint": { 91 | "builder": "@angular-devkit/build-angular:tslint", 92 | "options": { 93 | "tsConfig": [ 94 | "src/tsconfig.app.json", 95 | "src/tsconfig.spec.json" 96 | ], 97 | "exclude": [ 98 | "**/node_modules/**" 99 | ] 100 | } 101 | } 102 | } 103 | }, 104 | "angular-forms-example-e2e": { 105 | "root": "e2e/", 106 | "projectType": "application", 107 | "architect": { 108 | "e2e": { 109 | "builder": "@angular-devkit/build-angular:protractor", 110 | "options": { 111 | "protractorConfig": "e2e/protractor.conf.js", 112 | "devServerTarget": "angular-forms-example:serve" 113 | }, 114 | "configurations": { 115 | "production": { 116 | "devServerTarget": "angular-forms-example:serve:production" 117 | } 118 | } 119 | }, 120 | "lint": { 121 | "builder": "@angular-devkit/build-angular:tslint", 122 | "options": { 123 | "tsConfig": "e2e/tsconfig.e2e.json", 124 | "exclude": [ 125 | "**/node_modules/**" 126 | ] 127 | } 128 | } 129 | } 130 | } 131 | }, 132 | "defaultProject": "angular-forms-example" 133 | } 134 | -------------------------------------------------------------------------------- /e2e/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 | './src/**/*.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: require('path').join(__dirname, './tsconfig.e2e.json') 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('workspace-project 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 angular-forms-example!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/src/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/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-forms-example", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "^6.1.0", 15 | "@angular/cdk": "^6.2.0", 16 | "@angular/common": "^6.1.0", 17 | "@angular/compiler": "^6.1.0", 18 | "@angular/core": "^6.1.0", 19 | "@angular/forms": "^6.1.0", 20 | "@angular/http": "^6.1.0", 21 | "@angular/material": "^6.4.5", 22 | "@angular/platform-browser": "^6.1.0", 23 | "@angular/platform-browser-dynamic": "^6.1.0", 24 | "@angular/router": "^6.1.0", 25 | "bootstrap": "^4.1.3", 26 | "core-js": "^2.5.4", 27 | "rxjs": "^6.0.0", 28 | "zone.js": "~0.8.26" 29 | }, 30 | "devDependencies": { 31 | "@angular-devkit/build-angular": "~0.7.0", 32 | "@angular/cli": "~6.1.3", 33 | "@angular/compiler-cli": "^6.1.0", 34 | "@angular/language-service": "^6.1.0", 35 | "@types/jasmine": "~2.8.6", 36 | "@types/jasminewd2": "~2.0.3", 37 | "@types/node": "~8.9.4", 38 | "codelyzer": "~4.2.1", 39 | "jasmine-core": "~2.99.1", 40 | "jasmine-spec-reporter": "~4.2.1", 41 | "karma": "~1.7.1", 42 | "karma-chrome-launcher": "~2.2.0", 43 | "karma-coverage-istanbul-reporter": "~2.0.0", 44 | "karma-jasmine": "~1.1.1", 45 | "karma-jasmine-html-reporter": "^0.2.2", 46 | "protractor": "~5.3.0", 47 | "ts-node": "~5.0.1", 48 | "tslint": "~5.9.1", 49 | "typescript": "~2.7.2" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scopsy/angular-forms-example/1f3819bc092ef8d9fac0e8506f264428d03802cd/src/app/app.component.css -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { AppComponent } from './app.component'; 3 | import { APP_MODULE_DECLARATIONS, APP_MODULE_IMPORTS } from './app.module.dependencies'; 4 | describe('AppComponent', () => { 5 | beforeEach(async(() => { 6 | TestBed.configureTestingModule({ 7 | imports: [...APP_MODULE_IMPORTS], 8 | declarations: [ 9 | ...APP_MODULE_DECLARATIONS 10 | ], 11 | }).compileComponents(); 12 | })); 13 | 14 | it('should create the app', async(() => { 15 | const fixture = TestBed.createComponent(AppComponent); 16 | const app = fixture.debugElement.componentInstance; 17 | expect(app).toBeTruthy(); 18 | })); 19 | 20 | it(`should have as title 'angular-forms-example'`, async(() => { 21 | const fixture = TestBed.createComponent(AppComponent); 22 | const app = fixture.debugElement.componentInstance; 23 | expect(app.title).toEqual('angular-forms-example'); 24 | })); 25 | 26 | /* it('should render title in a h1 tag', async(() => { 27 | const fixture = TestBed.createComponent(AppComponent); 28 | fixture.detectChanges(); 29 | const compiled = fixture.debugElement.nativeElement; 30 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to angular-forms-example!'); 31 | }));*/ 32 | }); 33 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.css'] 7 | }) 8 | export class AppComponent { 9 | title = 'angular-forms-example'; 10 | } 11 | -------------------------------------------------------------------------------- /src/app/app.module.dependencies.ts: -------------------------------------------------------------------------------- 1 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { 4 | MatButtonModule, 5 | MatCheckboxModule, 6 | MatFormFieldModule, 7 | MatIconModule, 8 | MatInputModule, 9 | MatListModule, 10 | MatSelectModule, 11 | MatToolbarModule 12 | } from '@angular/material'; 13 | 14 | import { AppComponent } from './app.component'; 15 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 16 | import { PizzaFormContainerComponent } from './containers/pizza-form-container/pizza-form-container.component'; 17 | import { NavbarComponent } from './components/navbar/navbar.component'; 18 | import { SelectedPizzaViewerComponent } from './components/selected-pizza-viewer/selected-pizza-viewer.component'; 19 | import { PizzaListComponent } from './components/pizza-list/pizza-list.component'; 20 | import { CustomerDetailsComponent } from './components/customer-details/customer-details.component'; 21 | import { PizzaSizePickerComponent } from './components/pizza-size-picker/pizza-size-picker.component'; 22 | 23 | 24 | export const APP_MODULE_DECLARATIONS = [ 25 | AppComponent, 26 | PizzaFormContainerComponent, 27 | NavbarComponent, 28 | SelectedPizzaViewerComponent, 29 | PizzaListComponent, 30 | CustomerDetailsComponent, 31 | PizzaSizePickerComponent 32 | ]; 33 | 34 | export const APP_MODULE_IMPORTS = [ 35 | ReactiveFormsModule, 36 | FormsModule, 37 | MatButtonModule, 38 | MatInputModule, 39 | MatFormFieldModule, 40 | MatSelectModule, 41 | MatCheckboxModule, 42 | MatIconModule, 43 | MatListModule, 44 | MatToolbarModule, 45 | BrowserModule, 46 | BrowserAnimationsModule 47 | ]; 48 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { AppComponent } from './app.component'; 3 | import { APP_MODULE_DECLARATIONS, APP_MODULE_IMPORTS } from './app.module.dependencies'; 4 | 5 | @NgModule({ 6 | declarations: [...APP_MODULE_DECLARATIONS], 7 | imports: [...APP_MODULE_IMPORTS], 8 | providers: [], 9 | bootstrap: [AppComponent] 10 | }) 11 | export class AppModule { } 12 | -------------------------------------------------------------------------------- /src/app/components/customer-details/customer-details.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

5 | Customer Details 6 |

7 |
8 |
9 | 10 | 11 | 12 |
13 |
14 | 15 | 16 | 17 |
18 |
19 | 20 | 21 | 22 |
23 |
24 | 25 |
26 |
27 |

28 | Delivery Address 29 |

30 |
31 |
32 | 33 | 34 | 35 |
36 |
37 | 38 | 39 | 40 |
41 |
42 | 43 | 44 | 45 |
46 |
47 | 48 | 49 | 50 |
51 |
52 |
53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/app/components/customer-details/customer-details.component.scss: -------------------------------------------------------------------------------- 1 | 2 | .CustomerDetails { 3 | margin-top: 15px; 4 | } 5 | -------------------------------------------------------------------------------- /src/app/components/customer-details/customer-details.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit } from '@angular/core'; 2 | import { FormGroup } from '@angular/forms'; 3 | 4 | @Component({ 5 | selector: 'app-customer-details', 6 | templateUrl: './customer-details.component.html', 7 | styleUrls: ['./customer-details.component.scss'] 8 | }) 9 | export class CustomerDetailsComponent implements OnInit { 10 | @Input() group: FormGroup; 11 | constructor() { } 12 | 13 | ngOnInit() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/app/components/navbar/navbar.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 | Pizza App 4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/components/navbar/navbar.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-navbar', 5 | templateUrl: './navbar.component.html', 6 | styleUrls: [] 7 | }) 8 | export class NavbarComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/app/components/pizza-list/pizza-list.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |
5 |
6 |

7 | Pizzas order 8 |

9 |
10 |
11 |
16 | 17 | {{getPizzaTitle(pizza.value)}} 18 | 19 | 20 | 23 |
24 | 25 |
26 | add_circle 27 |
28 |
29 |
30 |
31 |
32 | -------------------------------------------------------------------------------- /src/app/components/pizza-list/pizza-list.component.scss: -------------------------------------------------------------------------------- 1 | .PizzaList { 2 | .PizzaList__item { 3 | border: 1px solid #f1f1f1; 4 | padding: 15px; 5 | margin-bottom: 10px; 6 | box-shadow: 0 1px 2px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); 7 | transition: all 0.3s cubic-bezier(.25,.8,.25,1); 8 | display: flex; 9 | align-items: center; 10 | justify-content: space-between; 11 | 12 | > span { 13 | white-space: nowrap; 14 | overflow: hidden; 15 | text-overflow: ellipsis; 16 | } 17 | 18 | &:hover { 19 | box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23); 20 | border: 1px solid #ededed; 21 | background: #f1f1f1; 22 | cursor: pointer; 23 | 24 | .PizzaList__item__icon { 25 | color: #D42434; 26 | } 27 | } 28 | 29 | &.PizzaList__item--active { 30 | background: #673ab7; 31 | 32 | span, 33 | .PizzaList__item__icon { 34 | color: white; 35 | } 36 | } 37 | 38 | &.PizzaList__item--has-error { 39 | border: 1px solid #D42434; 40 | } 41 | 42 | &.PizzaList__item--add { 43 | justify-content: center; 44 | 45 | &:hover { 46 | .PizzaList__item__icon { 47 | color: #673ab7; 48 | transform: rotate(90deg); 49 | } 50 | } 51 | } 52 | 53 | .PizzaList__item__icon { 54 | transition: all .3s cubic-bezier(.25,.8,.25,1); 55 | color: #b6b6b6; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/app/components/pizza-list/pizza-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; 2 | import { AbstractControl, FormArray, FormGroup } from '@angular/forms'; 3 | import { IPizzaItem, IToppingItem, PizzaSizeEnum } from '../../containers/pizza-form-container/services/pizza-form.interface'; 4 | import { PizzaFormService } from '../../containers/pizza-form-container/services/pizza-form.service'; 5 | 6 | @Component({ 7 | selector: 'app-pizza-list', 8 | templateUrl: './pizza-list.component.html', 9 | styleUrls: ['./pizza-list.component.scss'] 10 | }) 11 | export class PizzaListComponent implements OnInit { 12 | @Input() group: FormGroup; 13 | 14 | @Output() deletePizza = new EventEmitter(); 15 | @Output() addPizza = new EventEmitter(); 16 | @Output() pizzaSelected = new EventEmitter(); 17 | 18 | get pizzasArray(): FormArray { 19 | return this.group.get('pizzas') as FormArray; 20 | } 21 | 22 | constructor( 23 | private pizzaFormService: PizzaFormService 24 | ) { } 25 | 26 | ngOnInit() { 27 | } 28 | 29 | getPizzaListItemClassStates(pizza: AbstractControl, index: number) { 30 | return { 31 | 'PizzaList__item--active': this.group.get('selectedPizza').value === index, 32 | 'PizzaList__item--has-error': !pizza.valid && pizza.dirty 33 | }; 34 | } 35 | 36 | getPizzaTitle(pizza: IPizzaItem): string { 37 | const selectedToppings = this.pizzaFormService 38 | .getSelectedToppings((pizza.toppings as IToppingItem[])) 39 | .map(i => i.name); 40 | 41 | const toppingsString = this.getToppingsString(selectedToppings); 42 | const sizeString = this.getPizzaSizeTitle(pizza.size); 43 | 44 | return `${sizeString} pizza ${toppingsString}`; 45 | } 46 | 47 | private getToppingsString(toppings: string[]): string { 48 | if (!toppings || !toppings.length) return ''; 49 | 50 | return `- ${toppings.toString()}`; 51 | } 52 | 53 | private getPizzaSizeTitle(size: PizzaSizeEnum): string { 54 | let pizzaSize; 55 | switch (size) { 56 | case PizzaSizeEnum.SMALL: 57 | pizzaSize = 'S'; 58 | break; 59 | case PizzaSizeEnum.MEDIUM: 60 | pizzaSize = 'M'; 61 | break; 62 | case PizzaSizeEnum.LARGE: 63 | pizzaSize = 'L'; 64 | break; 65 | } 66 | 67 | return pizzaSize; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/app/components/pizza-size-picker/pizza-size-picker.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |
5 |
8 | SMALL 9 |
10 |
13 | MEDIUM 14 |
15 |
18 | LARGE 19 |
20 |
21 |
22 |
23 | -------------------------------------------------------------------------------- /src/app/components/pizza-size-picker/pizza-size-picker.component.scss: -------------------------------------------------------------------------------- 1 | .PizzaSizePicker { 2 | max-width: 700px; 3 | display: flex; 4 | 5 | .PizzaSizePicker__item { 6 | flex: 1; 7 | border: 1px solid #bdaaff; 8 | border-right: none; 9 | padding: 15px; 10 | text-align: center; 11 | transition: .3s all ease-in; 12 | 13 | &:last-child { 14 | border-right: 1px solid #bdaaff; 15 | } 16 | 17 | &:hover { 18 | cursor: pointer; 19 | background: #dac9ff; 20 | } 21 | 22 | &.PizzaSizePicker__item--active { 23 | background: #673ab7; 24 | color: white; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/app/components/pizza-size-picker/pizza-size-picker.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, forwardRef } from '@angular/core'; 2 | import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; 3 | import { PizzaSizeEnum } from '../../containers/pizza-form-container/services/pizza-form.interface'; 4 | 5 | @Component({ 6 | selector: 'app-pizza-size-picker', 7 | templateUrl: './pizza-size-picker.component.html', 8 | styleUrls: ['./pizza-size-picker.component.scss'], 9 | providers: [ 10 | { 11 | provide: NG_VALUE_ACCESSOR, 12 | useExisting: forwardRef(() => PizzaSizePickerComponent), 13 | multi: true 14 | } 15 | ] 16 | }) 17 | export class PizzaSizePickerComponent implements ControlValueAccessor { 18 | pizzaSize: PizzaSizeEnum; 19 | PizzaSizeEnum = PizzaSizeEnum; 20 | 21 | constructor() { } 22 | 23 | changeSize(size: PizzaSizeEnum) { 24 | this.pizzaSize = size; 25 | this.propagateChange(size); 26 | } 27 | 28 | propagateChange = (value: PizzaSizeEnum) => {}; 29 | writeValue(value: PizzaSizeEnum) { 30 | this.pizzaSize = value; 31 | } 32 | 33 | registerOnChange(fn) { 34 | this.propagateChange = fn; 35 | } 36 | 37 | registerOnTouched() {} 38 | } 39 | -------------------------------------------------------------------------------- /src/app/components/selected-pizza-viewer/selected-pizza-viewer.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 | {{selectedPizzaGroup.errors?.toppingPizzaSize?.message}} 6 |
7 |
8 |
9 | 10 |
11 |
12 |
Toppings
13 |
14 |
15 | 16 | {{topping.get('name').value}} 17 | 18 |
19 |
20 |
21 |
22 |
23 |
24 |

25 | You have not selected any pizzas yet. 26 |

27 | 31 |
32 |
33 |
34 | 35 | -------------------------------------------------------------------------------- /src/app/components/selected-pizza-viewer/selected-pizza-viewer.component.scss: -------------------------------------------------------------------------------- 1 | 2 | .PizzaSelectorView { 3 | min-height: 300px; 4 | margin-bottom: 15px; 5 | background: #f1f1f1; 6 | padding: 15px; 7 | 8 | &.PizzaSelectorView--empty { 9 | display: flex; 10 | align-items: center; 11 | justify-content: center; 12 | } 13 | 14 | .PizzaSelectorView__no-selected { 15 | width: 100%; 16 | height: 100%; 17 | display: flex; 18 | align-items: center; 19 | justify-content: center; 20 | flex-direction: column; 21 | 22 | h4 { 23 | font-weight: 200; 24 | text-align: center; 25 | font-size: 40px; 26 | } 27 | } 28 | } 29 | 30 | 31 | .ToppingsSelector { 32 | display: flex; 33 | align-content: center; 34 | align-items: center; 35 | flex-wrap: wrap; 36 | margin-top: 15px; 37 | 38 | .ToppingsSelector__item { 39 | margin-right: 15px; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/app/components/selected-pizza-viewer/selected-pizza-viewer.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; 2 | import { AbstractControl, FormArray } from '@angular/forms'; 3 | 4 | @Component({ 5 | selector: 'app-selected-pizza-viewer', 6 | templateUrl: './selected-pizza-viewer.component.html', 7 | styleUrls: ['./selected-pizza-viewer.component.scss'] 8 | }) 9 | export class SelectedPizzaViewerComponent implements OnInit { 10 | @Input() selectedPizzaGroup: AbstractControl; 11 | @Output() addPizza = new EventEmitter(); 12 | 13 | get toppingsArray(): FormArray { 14 | if (!this.selectedPizzaGroup) return; 15 | 16 | return this.selectedPizzaGroup.get('toppings') as FormArray; 17 | } 18 | 19 | constructor() { } 20 | 21 | ngOnInit() { 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/pizza-form-container.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 | {{form.errors?.noPizzas.message}} 6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | 15 | 16 |
17 |
18 | 19 |
20 |
21 | 22 |
23 |
24 |
25 |
26 | 29 | 32 |
33 |
34 |
35 |
36 | 40 | 41 |
42 |
43 |
44 | 45 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/pizza-form-container.component.scss: -------------------------------------------------------------------------------- 1 | .content { 2 | margin-top: 15px; 3 | } 4 | 5 | hr { 6 | display: block; 7 | height: 1px; 8 | border: 0; 9 | border-top: 1px solid #cccccc; 10 | margin: 1em 0; 11 | padding: 0; 12 | } 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/pizza-form-container.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AbstractControl, FormGroup } from '@angular/forms'; 3 | import { DEMO_PIZZA } from './services/demo-pizza-item'; 4 | import { PizzaFormValidatorsService } from './services/pizza-form-validators.service'; 5 | import { IPizzaFormInterface } from './services/pizza-form.interface'; 6 | import { PizzaFormService } from './services/pizza-form.service'; 7 | import { PizzaLoaderService } from './services/pizza-loader.service'; 8 | 9 | @Component({ 10 | selector: 'app-pizza-form-container', 11 | templateUrl: './pizza-form-container.component.html', 12 | styleUrls: ['./pizza-form-container.component.scss'], 13 | providers: [ 14 | PizzaFormService, 15 | PizzaFormValidatorsService, 16 | PizzaLoaderService 17 | ] 18 | }) 19 | export class PizzaFormContainerComponent implements OnInit { 20 | editMode = false; 21 | get form(): FormGroup { 22 | return this.pizzaFormService.form; 23 | } 24 | 25 | get selectedPizzaGroup(): AbstractControl { 26 | if (!this.pizzaFormService.pizzasArray.length) return; 27 | 28 | return this.pizzaFormService.pizzasArray.at(this.form.get('selectedPizza').value); 29 | } 30 | 31 | constructor( 32 | private pizzaLoaderService: PizzaLoaderService, 33 | private pizzaFormService: PizzaFormService 34 | ) { } 35 | 36 | ngOnInit() { 37 | // here you can check the page url if a pizza order id was specified 38 | // and load it from the server 39 | if (this.editMode) { 40 | this.pizzaLoaderService.loadPizzaForEdit(DEMO_PIZZA); 41 | } 42 | } 43 | 44 | async submit(data: IPizzaFormInterface) { 45 | if (!this.pizzaFormService.isValid) { 46 | return; 47 | } 48 | 49 | const order: IPizzaFormInterface = this.pizzaFormService.createPizzaOrderDto(data); 50 | 51 | alert(`Thanks ${order.customerDetails.firstName}, the pizza is on the way!`); 52 | 53 | if (this.editMode) { 54 | // update api endpoint call 55 | } else { 56 | // create api endpoint call 57 | } 58 | } 59 | 60 | reset() { 61 | this.pizzaFormService.resetForm(); 62 | } 63 | 64 | onPizzaAdd() { 65 | this.pizzaFormService.addPizza(); 66 | this.pizzaFormService.selectPizzaForEdit(this.pizzaFormService.pizzasArray.length - 1); 67 | } 68 | 69 | onPizzaDelete(index: number) { 70 | this.pizzaFormService.deletePizza(index); 71 | } 72 | 73 | onPizzaSelected(index: number) { 74 | this.pizzaFormService.selectPizzaForEdit(index); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/services/demo-pizza-item.ts: -------------------------------------------------------------------------------- 1 | import { IPizzaFormInterface, PizzaSizeEnum, PizzaToppingsEnum } from './pizza-form.interface'; 2 | 3 | export const DEMO_PIZZA: IPizzaFormInterface = { 4 | customerDetails: { 5 | address: { 6 | floor: 1, 7 | street: 'Test street', 8 | houseNum: '44', 9 | city: 'New York' 10 | }, 11 | lastName: 'Lover', 12 | firstName: 'Pizza', 13 | phoneNumber: '100100100', 14 | }, 15 | pizzas: [{ 16 | toppings: [PizzaToppingsEnum.BACON, PizzaToppingsEnum.MUSHROOMS, PizzaToppingsEnum.OLIVES] as any, 17 | size: PizzaSizeEnum.MEDIUM 18 | }] 19 | }; 20 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/services/pizza-form-validators.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject } from '@angular/core/testing'; 2 | import { FormArray, FormGroup, ValidatorFn } from '@angular/forms'; 3 | import { AppModule } from '../../../app.module'; 4 | 5 | import { PizzaFormValidatorsService } from './pizza-form-validators.service'; 6 | 7 | describe('PizzaFormValidatorsService', () => { 8 | let validatorService: PizzaFormValidatorsService; 9 | 10 | beforeEach(() => { 11 | TestBed.configureTestingModule({ 12 | imports: [], 13 | providers: [PizzaFormValidatorsService] 14 | }); 15 | }); 16 | 17 | beforeEach(inject([PizzaFormValidatorsService], (service: PizzaFormValidatorsService) => { 18 | validatorService = service; 19 | })); 20 | 21 | describe('Form Validator', () => { 22 | let formValidator: ValidatorFn; 23 | beforeEach(() => { 24 | formValidator = validatorService.formValidator(); 25 | }); 26 | 27 | it('should return error when there is no pizza', () => { 28 | const result = formValidator(new FormGroup({ 29 | pizzas: new FormArray([]) 30 | })); 31 | 32 | expect(result.noPizzas).toBeTruthy(); 33 | }); 34 | 35 | it('should not return error when pizzas exist', () => { 36 | const result = formValidator(new FormGroup({ 37 | pizzas: new FormArray([ 38 | new FormGroup({}) 39 | ]) 40 | })); 41 | 42 | expect(result).toBe(null); 43 | }); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/services/pizza-form-validators.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { FormArray, FormControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms'; 3 | import { IToppingItem, PizzaSizeEnum } from './pizza-form.interface'; 4 | 5 | @Injectable() 6 | export class PizzaFormValidatorsService { 7 | 8 | constructor() { } 9 | 10 | formValidator(): ValidatorFn { 11 | return (control: FormGroup): ValidationErrors | null => { 12 | const errors: ValidationErrors = {}; 13 | 14 | if (!(control.get('pizzas') as FormArray).length) { 15 | errors.noPizzas = { 16 | message: 'You must select at least one pizza to order' 17 | }; 18 | } 19 | 20 | return Object.keys(errors).length ? errors : null; 21 | }; 22 | } 23 | 24 | pizzaItemValidator(): ValidatorFn { 25 | return (control: FormGroup): ValidationErrors | null => { 26 | const errors: ValidationErrors = {}; 27 | 28 | const pizzaSize: PizzaSizeEnum = control.get('size').value; 29 | const pizzaToppings: IToppingItem[] = control.get('toppings').value.filter(i => i.selected); 30 | 31 | if (pizzaSize !== PizzaSizeEnum.LARGE && pizzaToppings.length > 4) { 32 | errors.toppingPizzaSize = { 33 | message: 'To use more then 4 toppings you must selected large pizza' 34 | }; 35 | } 36 | 37 | return Object.keys(errors).length ? errors : null; 38 | }; 39 | } 40 | 41 | validateAllFormFields(formGroup: FormGroup) { 42 | Object.keys(formGroup.controls).forEach(field => { 43 | const control = formGroup.get(field); 44 | 45 | if (control instanceof FormControl) { 46 | control.markAsTouched({ onlySelf: true }); 47 | } else if (control instanceof FormGroup) { 48 | this.validateAllFormFields(control); 49 | } 50 | }); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/services/pizza-form.interface.ts: -------------------------------------------------------------------------------- 1 | export interface IPizzaFormInterface { 2 | selectedPizza?: IPizzaItem; 3 | pizzas: IPizzaItem[]; 4 | customerDetails: ICustomerDetails; 5 | } 6 | 7 | export interface IToppingItem { 8 | name: PizzaToppingsEnum; 9 | selected: boolean; 10 | } 11 | 12 | export interface IPizzaItem { 13 | size: PizzaSizeEnum; 14 | /** 15 | * A small hack for imitating a different model returned from server, 16 | * for the simplicity sake the same interface was used. 17 | * In real life the server model may vary from the form model. 18 | * In this case you need to maintain both the server model interface and the client form interface. 19 | */ 20 | toppings: IToppingItem[] | PizzaToppingsEnum[]; 21 | } 22 | 23 | export interface ICustomerDetails { 24 | firstName: string; 25 | lastName: string; 26 | phoneNumber: string; 27 | address: { 28 | street: string; 29 | houseNum: string; 30 | city: string; 31 | floor: number; 32 | }; 33 | } 34 | 35 | export enum PizzaSizeEnum { 36 | SMALL = 1, 37 | MEDIUM = 2, 38 | LARGE = 3 39 | } 40 | 41 | export enum PizzaToppingsEnum { 42 | SAUSAGE = 'Sausage', 43 | PEPPERONI = 'Pepperoni', 44 | HAM = 'Ham', 45 | OLIVES = 'Olives', 46 | BACON = 'Bacon', 47 | CORN = 'Corn', 48 | PINEAPPLE = 'Pineapple', 49 | MUSHROOMS = 'Mushrooms' 50 | } 51 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/services/pizza-form.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { inject, TestBed } from '@angular/core/testing'; 2 | import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; 3 | import { PizzaFormValidatorsService } from './pizza-form-validators.service'; 4 | import { IPizzaFormInterface, PizzaSizeEnum, PizzaToppingsEnum } from './pizza-form.interface'; 5 | 6 | import { PizzaFormService } from './pizza-form.service'; 7 | import { PizzaLoaderService } from './pizza-loader.service'; 8 | 9 | describe('PizzaFormService', () => { 10 | let pizzaFormService: PizzaFormService; 11 | beforeEach(() => { 12 | TestBed.configureTestingModule({ 13 | imports: [ReactiveFormsModule, FormsModule], 14 | providers: [PizzaFormService, PizzaLoaderService, PizzaFormValidatorsService] 15 | }); 16 | }); 17 | 18 | beforeEach(inject([PizzaFormService], (service: PizzaFormService) => { 19 | pizzaFormService = service; 20 | })); 21 | 22 | describe('Service initialization', () => { 23 | it('should initialize a form group when class gets constructed', function () { 24 | expect(pizzaFormService.form instanceof FormGroup).toEqual(true); 25 | }); 26 | 27 | it('should initialize form properly', () => { 28 | expect(pizzaFormService.form.get('pizzas').value.length).toBe(0); 29 | expect(pizzaFormService.form.get('selectedPizza').value).toBeNull(); 30 | expect(pizzaFormService.form.valid).toEqual(false); 31 | }); 32 | }); 33 | 34 | describe('Service behaviour', () => { 35 | it('should calculate if the form is valid', () => { 36 | pizzaFormService.form = new FormGroup({ 37 | name: new FormControl('', Validators.required) 38 | }); 39 | expect(pizzaFormService.isValid).toBe(false); 40 | pizzaFormService.form.get('name').setValue('test'); 41 | 42 | expect(pizzaFormService.isValid).toBe(true); 43 | }); 44 | 45 | it('should add pizza for the pizzas array', function () { 46 | expect(pizzaFormService.form.get('pizzas').value.length).toEqual(0); 47 | pizzaFormService.addPizza(); 48 | expect(pizzaFormService.form.get('pizzas').value.length).toEqual(1); 49 | }); 50 | 51 | it('should mark the form as dirty after pizza added', function () { 52 | expect(pizzaFormService.form.dirty).toEqual(false); 53 | pizzaFormService.addPizza(); 54 | expect(pizzaFormService.form.dirty).toEqual(true); 55 | }); 56 | 57 | it('should select a pizza for edit mode', () => { 58 | pizzaFormService.addPizza(); 59 | pizzaFormService.addPizza(); 60 | 61 | pizzaFormService.selectPizzaForEdit(0); 62 | expect(pizzaFormService.form.get('selectedPizza').value).toEqual(0); 63 | }); 64 | 65 | it('should delete an added pizza', function () { 66 | pizzaFormService.addPizza(); 67 | expect(pizzaFormService.form.get('pizzas').value.length).toEqual(1); 68 | pizzaFormService.deletePizza(0); 69 | expect(pizzaFormService.form.get('pizzas').value.length).toEqual(0); 70 | }); 71 | 72 | describe('Pizza Dto construction', () => { 73 | let demoData: IPizzaFormInterface; 74 | beforeEach(() => { 75 | demoData = { 76 | pizzas: [{ 77 | toppings: [{ 78 | selected: false, 79 | name: PizzaToppingsEnum.PEPPERONI 80 | }, { 81 | selected: true, 82 | name: PizzaToppingsEnum.HAM 83 | }, { 84 | selected: true, 85 | name: PizzaToppingsEnum.OLIVES 86 | }], 87 | size: PizzaSizeEnum.MEDIUM 88 | }], 89 | customerDetails: { 90 | phoneNumber: '123' 91 | } 92 | } as any; 93 | }); 94 | 95 | it('should create a pizza dto from a data object', function () { 96 | const constructedData = pizzaFormService.createPizzaOrderDto(demoData); 97 | expect(constructedData.pizzas.length).toEqual(1); 98 | expect(constructedData.customerDetails.phoneNumber).toEqual('123'); 99 | }); 100 | 101 | it('should extract selected toppings only', function () { 102 | const constructedData = pizzaFormService.createPizzaOrderDto(demoData); 103 | expect(constructedData.pizzas[0].toppings.length).toEqual(2); 104 | }); 105 | 106 | it('should convert topping data structure to enum array', function () { 107 | const constructedData = pizzaFormService.createPizzaOrderDto(demoData); 108 | expect(constructedData.pizzas[0].toppings[0]).toEqual(PizzaToppingsEnum.HAM); 109 | }); 110 | }); 111 | 112 | it('should return only selected toppings', function () { 113 | const selectedToppings = pizzaFormService.getSelectedToppings([{ 114 | name: PizzaToppingsEnum.OLIVES, 115 | selected: false 116 | }, { 117 | name: PizzaToppingsEnum.HAM, 118 | selected: true 119 | }, { 120 | name: PizzaToppingsEnum.PEPPERONI, 121 | selected: false 122 | }]); 123 | 124 | expect(selectedToppings.length).toEqual(1); 125 | expect(selectedToppings[0].name).toEqual(PizzaToppingsEnum.HAM); 126 | }); 127 | }); 128 | }); 129 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/services/pizza-form.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; 3 | import { PizzaFormValidatorsService } from './pizza-form-validators.service'; 4 | import { IPizzaFormInterface, IToppingItem, PizzaSizeEnum, PizzaToppingsEnum } from './pizza-form.interface'; 5 | 6 | @Injectable() 7 | export class PizzaFormService { 8 | public availableToppings = [...Object.values(PizzaToppingsEnum)]; 9 | public form: FormGroup; 10 | 11 | constructor( 12 | private pizzaValidatorsService: PizzaFormValidatorsService, 13 | private fb: FormBuilder 14 | ) { 15 | this.form = this.fb.group({ 16 | selectedPizza: null, 17 | pizzas: this.fb.array([]), 18 | customerDetails: this.fb.group({ 19 | firstName: [null, Validators.required], 20 | lastName: [null, Validators.required], 21 | phoneNumber: [null, Validators.required], 22 | address: this.fb.group({ 23 | street: [null, Validators.required], 24 | houseNum: [null, Validators.required], 25 | city: [null, Validators.required], 26 | floor: [null, Validators.required], 27 | }) 28 | }) 29 | }, { 30 | validator: this.pizzaValidatorsService.formValidator() 31 | }); 32 | } 33 | 34 | get pizzasArray(): FormArray { 35 | return this.form.get('pizzas') as FormArray; 36 | } 37 | 38 | get isValid(): boolean { 39 | if (!this.form.valid) { 40 | this.pizzaValidatorsService.validateAllFormFields(this.form); 41 | return false; 42 | } 43 | 44 | return true; 45 | } 46 | 47 | selectPizzaForEdit(index: number) { 48 | this.form.get('selectedPizza').setValue(index); 49 | } 50 | 51 | addPizza(): FormGroup { 52 | const pizzaGroup = this.getPizzaFormGroup(); 53 | this.pizzasArray.push(this.getPizzaFormGroup()); 54 | 55 | this.form.markAsDirty(); 56 | 57 | return pizzaGroup; 58 | } 59 | 60 | deletePizza(index: number): void { 61 | this.pizzasArray.removeAt(index); 62 | this.form.markAsDirty(); 63 | } 64 | 65 | getPizzaFormGroup(size: PizzaSizeEnum = PizzaSizeEnum.MEDIUM): FormGroup { 66 | return this.fb.group({ 67 | size: [size], 68 | toppings: this.mapToCheckboxArrayGroup(this.availableToppings) 69 | }, { 70 | validator: this.pizzaValidatorsService.pizzaItemValidator() 71 | }); 72 | } 73 | 74 | /** 75 | * Creates a pizza DTO Object using the server pizza interface 76 | * In this example it is the same except the toppings array, 77 | * so for simplicity i used the same interface, 78 | * usually the return object will be of different type 79 | */ 80 | createPizzaOrderDto(data: IPizzaFormInterface): IPizzaFormInterface { 81 | const order = { 82 | customerDetails: data.customerDetails, 83 | pizzas: data.pizzas 84 | }; 85 | 86 | for (const pizza of order.pizzas) { 87 | pizza.toppings = this.getSelectedToppings(pizza.toppings as IToppingItem[]) 88 | .map((i) => { 89 | return i.name; 90 | }); 91 | } 92 | 93 | return order; 94 | } 95 | 96 | getSelectedToppings(toppings: IToppingItem[]): IToppingItem[] { 97 | return toppings.filter(i => i.selected); 98 | } 99 | 100 | resetForm() { 101 | while (this.pizzasArray.length) { 102 | this.pizzasArray.removeAt(0); 103 | } 104 | 105 | this.form.reset(); 106 | } 107 | 108 | /** 109 | * Create a mapping of a string based dataset 110 | * to a form array suitable for a multi checkbox array selection. 111 | * this provides a more concise solution 112 | * as oppose to working with [true, false, false, true] 113 | */ 114 | private mapToCheckboxArrayGroup(data: string[]): FormArray { 115 | return this.fb.array(data.map((i) => { 116 | return this.fb.group({ 117 | name: i, 118 | selected: false 119 | }); 120 | })); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/services/pizza-loader.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { inject, TestBed } from '@angular/core/testing'; 2 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 3 | import { PizzaFormValidatorsService } from './pizza-form-validators.service'; 4 | import { PizzaToppingsEnum } from './pizza-form.interface'; 5 | import { PizzaFormService } from './pizza-form.service'; 6 | 7 | import { PizzaLoaderService } from './pizza-loader.service'; 8 | 9 | describe('PizzaLoaderService', () => { 10 | beforeEach(() => { 11 | TestBed.configureTestingModule({ 12 | imports: [ReactiveFormsModule, FormsModule], 13 | providers: [PizzaLoaderService, PizzaFormService, PizzaFormValidatorsService] 14 | }); 15 | }); 16 | 17 | it('should change selected state of selected items', inject([PizzaLoaderService], (service: PizzaLoaderService) => { 18 | const TOPPINGS_DATA = [{ 19 | selected: false, 20 | name: PizzaToppingsEnum.OLIVES 21 | }, { 22 | selected: false, 23 | name: PizzaToppingsEnum.MUSHROOMS 24 | }, { 25 | selected: false, 26 | name: PizzaToppingsEnum.HAM 27 | }]; 28 | 29 | const result = service.prefillToppingsSelection(TOPPINGS_DATA, [PizzaToppingsEnum.MUSHROOMS, PizzaToppingsEnum.HAM]); 30 | expect(result[0].selected).toBe(false); 31 | expect(result[2].selected).toBe(true); 32 | })); 33 | }); 34 | -------------------------------------------------------------------------------- /src/app/containers/pizza-form-container/services/pizza-loader.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { IPizzaFormInterface, IToppingItem, PizzaToppingsEnum } from './pizza-form.interface'; 3 | import { PizzaFormService } from './pizza-form.service'; 4 | 5 | @Injectable() 6 | export class PizzaLoaderService { 7 | 8 | constructor( 9 | private pizzaFormService: PizzaFormService 10 | ) { 11 | 12 | } 13 | 14 | loadPizzaForEdit(data: IPizzaFormInterface): void { 15 | this.pizzaFormService.form.patchValue({ 16 | customerDetails: { 17 | ...data.customerDetails 18 | } 19 | }); 20 | 21 | for (const pizza of data.pizzas) { 22 | const group = this.pizzaFormService.addPizza(); 23 | group.patchValue({ 24 | size: pizza.size, 25 | toppings: this.prefillToppingsSelection(group.get('toppings').value, pizza.toppings as PizzaToppingsEnum[]) 26 | }); 27 | } 28 | } 29 | 30 | prefillToppingsSelection(toppings: IToppingItem[], selectedToppings: PizzaToppingsEnum[]): IToppingItem[] { 31 | return toppings.map((i) => { 32 | if (selectedToppings.includes(i.name)) { 33 | i.selected = true; 34 | } 35 | 36 | return i; 37 | }); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scopsy/angular-forms-example/1f3819bc092ef8d9fac0e8506f264428d03802cd/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/browserslist: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # For IE 9-11 support, please uncomment the last line of the file and adjust as needed 5 | > 0.5% 6 | last 2 versions 7 | Firefox ESR 8 | not dead 9 | # IE 9-11 -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * In development mode, for easier debugging, you can ignore zone related error 11 | * stack frames such as `zone.run`/`zoneDelegate.invokeTask` by importing the 12 | * below file. Don't forget to comment it out in production mode 13 | * because it will have a performance impact when errors are thrown 14 | */ 15 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 16 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scopsy/angular-forms-example/1f3819bc092ef8d9fac0e8506f264428d03802cd/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | AngularFormsExample 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/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-devkit/build-angular'], 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-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage'), 20 | reports: ['html', 'lcovonly'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false 30 | }); 31 | }; -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.log(err)); 13 | -------------------------------------------------------------------------------- /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 | * Web Animations `@angular/platform-browser/animations` 51 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 52 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 53 | **/ 54 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 55 | 56 | /** 57 | * By default, zone.js will patch all possible macroTask and DomEvents 58 | * user can disable parts of macroTask/DomEvents patch by setting following flags 59 | */ 60 | 61 | // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 62 | // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 63 | // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 64 | 65 | /* 66 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 67 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 68 | */ 69 | // (window as any).__Zone_enable_cross_context_check = true; 70 | 71 | /*************************************************************************************************** 72 | * Zone JS is required by default for Angular itself. 73 | */ 74 | import 'zone.js/dist/zone'; // Included with Angular CLI. 75 | 76 | 77 | 78 | /*************************************************************************************************** 79 | * APPLICATION IMPORTS 80 | */ 81 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | @import '~bootstrap/scss/bootstrap-reboot'; 3 | @import '~bootstrap/scss/bootstrap-grid'; 4 | 5 | .full-width-input { 6 | width: 100%; 7 | } 8 | 9 | .mg-top-15 { 10 | margin-top: 15px; 11 | } 12 | 13 | .mg-bottom-15 { 14 | margin-bottom: 15px; 15 | } 16 | 17 | .pull-right { 18 | float: right; 19 | } 20 | 21 | .ValidationErrorLabel { 22 | width: 100%; 23 | background: #D42434; 24 | color: white; 25 | padding: 15px; 26 | border-radius: 3px; 27 | } 28 | -------------------------------------------------------------------------------- /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/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "exclude": [ 8 | "src/test.ts", 9 | "**/*.spec.ts" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "test.ts", 12 | "polyfills.ts" 13 | ], 14 | "include": [ 15 | "**/*.spec.ts", 16 | "**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "module": "es2015", 9 | "moduleResolution": "node", 10 | "emitDecoratorMetadata": true, 11 | "experimentalDecorators": true, 12 | "target": "es5", 13 | "typeRoots": [ 14 | "node_modules/@types" 15 | ], 16 | "lib": [ 17 | "es2017", 18 | "dom" 19 | ] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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": false, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs/Rx" 22 | ], 23 | "import-spacing": true, 24 | "indent": [ 25 | true, 26 | "spaces" 27 | ], 28 | "interface-over-type-literal": true, 29 | "label-position": true, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-arg": true, 47 | "no-bitwise": true, 48 | "no-console": [ 49 | true, 50 | "debug", 51 | "info", 52 | "time", 53 | "timeEnd", 54 | "trace" 55 | ], 56 | "no-construct": true, 57 | "no-debugger": true, 58 | "no-duplicate-super": true, 59 | "no-empty": false, 60 | "no-empty-interface": true, 61 | "no-eval": true, 62 | "no-inferrable-types": [ 63 | true, 64 | "ignore-params" 65 | ], 66 | "no-misused-new": true, 67 | "no-non-null-assertion": true, 68 | "no-shadowed-variable": true, 69 | "no-string-literal": false, 70 | "no-string-throw": true, 71 | "no-switch-case-fall-through": true, 72 | "no-trailing-whitespace": true, 73 | "no-unnecessary-initializer": true, 74 | "no-unused-expression": true, 75 | "no-use-before-declare": true, 76 | "no-var-keyword": true, 77 | "object-literal-sort-keys": false, 78 | "one-line": [ 79 | true, 80 | "check-open-brace", 81 | "check-catch", 82 | "check-else", 83 | "check-whitespace" 84 | ], 85 | "prefer-const": true, 86 | "quotemark": [ 87 | true, 88 | "single" 89 | ], 90 | "radix": true, 91 | "semicolon": [ 92 | true, 93 | "always" 94 | ], 95 | "triple-equals": [ 96 | true, 97 | "allow-null-check" 98 | ], 99 | "typedef-whitespace": [ 100 | true, 101 | { 102 | "call-signature": "nospace", 103 | "index-signature": "nospace", 104 | "parameter": "nospace", 105 | "property-declaration": "nospace", 106 | "variable-declaration": "nospace" 107 | } 108 | ], 109 | "unified-signatures": true, 110 | "variable-name": false, 111 | "whitespace": [ 112 | true, 113 | "check-branch", 114 | "check-decl", 115 | "check-operator", 116 | "check-separator", 117 | "check-type" 118 | ], 119 | "no-output-on-prefix": true, 120 | "use-input-property-decorator": true, 121 | "use-output-property-decorator": true, 122 | "use-host-property-decorator": true, 123 | "no-input-rename": true, 124 | "no-output-rename": true, 125 | "use-life-cycle-interface": true, 126 | "use-pipe-transform-interface": true, 127 | "component-class-suffix": true, 128 | "directive-class-suffix": true 129 | } 130 | } 131 | --------------------------------------------------------------------------------