Coder Social home page Coder Social logo

deborahk / angular-reactiveforms Goto Github PK

View Code? Open in Web Editor NEW
477.0 477.0 760.0 994 KB

Materials for my Pluralsight course: Angular Reactive Forms.

Home Page: https://app.pluralsight.com/library/courses/angular-2-reactive-forms

License: MIT License

CSS 0.94% TypeScript 56.00% HTML 37.24% JavaScript 5.83%

angular-reactiveforms's Introduction

angular-reactiveforms's People

Contributors

deborahk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-reactiveforms's Issues

npm test has two failures

Hi Deborah,

When I run npm test two tests fail. These are default tests that probably worked until you changed the app.component.html file.

Best regards,

Karl

ng serve throws : The "@angular/compiler-cli" package was not properly installed - Error

On doing ng serve on Demo-Start-Updated folder gives below error.

The "@angular/compiler-cli" package was not properly installed. Error: TypeError: Object prototype may only be an Object or null: undefined
Error: The "@angular/compiler-cli" package was not properly installed. Error: TypeError: Object prototype may only be an Object or null: undefined
at Object. (C:\Noor\Practice\Angular Reactive Forms\SecondHandson\node_modules@angular\cli\node_modules@ngtools\webpack\src\index.j
s:14:11)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Module.require (module.js:517:17)
at require (internal/module.js:11:18)
at Object. (C:\Noor\Practice\Angular Reactive Forms\SecondHandson\node_modules@angular\cli\tasks\eject.js:10:19)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Module.require (module.js:517:17)
at require (internal/module.js:11:18)

Below is my package.json file

{ "name": "product-management", "version": "1.1.0", "author": "Deborah Kurata", "description": "Package for the demo form application", "scripts": { "build": "tsc -p src/", "build:watch": "tsc -p src/ -w", "serve": "lite-server -c=bs-config.json", "prestart": "npm run build", "start": "concurrently \"npm run build:watch\" \"npm run serve\"", "lint": "tslint ./src/**/*.ts -t verbose" }, "license": "ISC", "dependencies": { "@angular/common": "~4.0.0", "@angular/compiler": "~4.0.0", "@angular/core": "~4.0.0", "@angular/forms": "~4.0.0", "@angular/http": "~4.0.0", "@angular/platform-browser": "~4.0.0", "@angular/platform-browser-dynamic": "~4.0.0", "@angular/router": "~4.0.0", "angular-in-memory-web-api": "~0.3.0", "systemjs": "0.19.40", "core-js": "^2.4.1", "rxjs": "5.0.1", "zone.js": "^0.8.4", "bootstrap": "^3.3.6" }, "devDependencies": { "@angular/cli": "^1.4.5", "@ngtools/webpack": "^1.2.13", "@types/node": "^6.0.46", "canonical-path": "0.0.2", "concurrently": "^3.2.0", "lite-server": "^2.2.2", "rimraf": "^2.5.4", "tslint": "^3.15.1", "typescript": "~2.1.0" }, "repository": {} }

Cannot find control with path: angular2

I m getting below error when converting formarray of formgroups to html view.

Cannot find control with path: 'categories -> 0'

ts file
private categories : any= [{name: 'Strict',selected : false},
{name: 'Moderate',selected : true},
{name: 'Flexible',selected : true}];

let allCategories: FormArray = new FormArray([]);
for (let i = 0; i < this.categories.length; i++) {
let fg = new FormGroup({});
fg.addControl(this.categories[i].name, new FormControl(this.categories[i].selected))
allCategories.push(fg)
}

form initialization
categories: allCategories,

Html part

{{category.name}}
Thanks in advance

Deborah's next course: ACME Products created with Angular-cli

My suggestions: Redo your ACME Products app with Angular-Cli using as many Angular Schematics feature as possible.
My reasonings: Angular-cli is such a critical piece in the angular dev process. It just does not make sense to dev a new angular app without the cli!

regards
Hans

Not Working

Hi this solution is not working with my machine.
image

You seem to not be depending on "@angular/core" and/or "rxjs". This is an error

Hi,
I was trying to install new version of this project in new folder structure in my PC and I have
npm --version : 4.4.4 && angular-cli global: "6.0.3" && Git vresion 2.17.0
and to save some volume in my machine, I copied package.json & package-lock.,json to the root folder where the project "Angular-ReactiveForms" downloaded and then run command "npm i" to install the node-modules so I can reference it in all other projects.
now after getting into APM-Updated folder and run command "ng serve" or "ng Build" I get the error:
"You seem to not be depending on "@angular/core" and/or "rxjs". This is an error"

Appreciate your help on this error,

Create a Form component and an Array Component

You created the Address inside the Form, but it would be great to create the one Address component that could be added inside the form.
And it could be even better to create one AddressArray component using the previous Address component.

this way would be very transparent to use one address, or to use the array when it's necessary

How to setup Nested Form Groups in the APM updated?

Hi,

I watched your course on pluralsight which was awesome. Thanks for doing that one. I am confused on how to set up nested form groups to then have the generic validator process the messages.

You have this:

this.validationMessages = {
productName: {
required: 'Product name is required.',
minlength: 'Product name must be at least three characters.',
maxlength: 'Product name cannot exceed 50 characters.'
},
productCode: {
required: 'Product code is required.'
},
starRating: {
range: 'Rate the product between 1 (lowest) and 5 (highest).'
}
};

    // Define an instance of the validator for use with this form, 
    // passing in this form's set of validation messages.
    this.genericValidator = new GenericValidator(this.validationMessages);

// product form
this.productForm = this.fb.group({
productName: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(50)]],
productCode: ['', Validators.required],
starRating: ['', NumberValidators.range(1, 5)],
tags: this.fb.array([]),
description: ''
});

I tried doing something similar but we have nested form groups but I can't get it to work.

for example if the this.productForm looked like this with productCode being nested:
this.productForm = this.fb.group({
productName: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(50)]],
productCode: this.fb.group({
internal: ['', Validators.required],
external: ['', Validators.required]
}),
starRating: ['', NumberValidators.range(1, 5)],
tags: this.fb.array([]),
description: ''
});

How would you write the this.validationMessages? I tried a nested object like this but it did not work.
this.validationMessages = {
productName: {
required: 'Product name is required.',
minlength: 'Product name must be at least three characters.',
maxlength: 'Product name cannot exceed 50 characters.'
},
productCode: {
internal: {
required: 'Internal Product code is required.'
}
external: {
required: 'External Product code is required.'
}
},
starRating: {
range: 'Rate the product between 1 (lowest) and 5 (highest).'
}
};

Any suggestions?

Generic validator with AsyncValidator

I'm just opening a little discussion on this subject.

I wonder if this part of the code will work with AsyncValidators ?
merge(this.productForm.valueChanges, ...controlBlurs).pipe( debounceTime(800) ).subscribe(value => { this.displayMessage = this.genericValidator.processMessages(this.productForm); });

My guess is this.genericValidator.processMessages(this.productForm) will end before AsyncValidators and so async errors won't be displayed. Maybe the errors will be displayed the next time this.genericValidator.processMessages(this.productForm) run again.

Error when runing with npm start

After you download the project if you run the usual commands, it produces an error:

cd Angular2-ReactiveForms-master/APM/
npm install
npm start

This is the output it produces:

> [email protected] start /home/jabellota/Escritorio/Angular2-ReactiveForms-master/APM
> tsc && concurrently "tsc -w" "lite-server" 

app/products/product-edit.component.ts(152,28): error TS2339: Property 'assign' does not exist on type 'ObjectConstructor'.
app/shared/generic-validator.ts(34,28): error TS2339: Property 'assign' does not exist on type 'ObjectConstructor'.
node_modules/@angular/common/src/pipes/async_pipe.d.ts(44,38): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/aot/compiler.d.ts(32,38): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/aot/compiler_host.d.ts(19,33): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/directive_normalizer.d.ts(38,72): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/directive_normalizer.d.ts(40,74): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/i18n/extractor.d.ts(17,33): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/i18n/extractor.d.ts(26,35): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/jit/compiler.d.ts(44,49): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/jit/compiler.d.ts(46,65): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/metadata_resolver.d.ts(58,104): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/resource_loader.d.ts(13,23): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/util.d.ts(25,18): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/compiler/src/util.d.ts(26,46): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/application_init.d.ts(16,18): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/application_ref.d.ts(116,67): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/application_ref.d.ts(132,101): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/application_ref.d.ts(158,67): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/application_ref.d.ts(160,101): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/lang.d.ts(12,17): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/lang.d.ts(13,17): error TS2304: Cannot find name 'Set'.
node_modules/@angular/core/src/linker/compiler.d.ts(53,49): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/linker/compiler.d.ts(61,65): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/linker/ng_module_factory_loader.d.ts(14,34): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/linker/system_js_ng_module_factory_loader.d.ts(28,25): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/util/lang.d.ts(8,53): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/platform-browser-dynamic/src/resource_loader/resource_loader_impl.d.ts(10,23): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/config.d.ts(307,62): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/interfaces.d.ts(78,99): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/interfaces.d.ts(157,109): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/interfaces.d.ts(227,115): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/interfaces.d.ts(297,89): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/interfaces.d.ts(367,50): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/router.d.ts(392,70): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/router.d.ts(414,59): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/router/src/utils/collection.d.ts(35,58): error TS2304: Cannot find name 'Promise'.
node_modules/@types/core-js/index.d.ts(47,36): error TS2304: Cannot find name 'Iterable'.
node_modules/@types/core-js/index.d.ts(350,48): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(351,52): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(352,34): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(353,34): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(354,34): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(355,61): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(356,60): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(357,65): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(357,97): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(358,60): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(359,58): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(360,59): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(361,58): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(362,61): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(362,117): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(363,42): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(365,81): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(366,78): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(367,76): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(368,73): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(431,6): error TS2304: Cannot find name 'Symbol'.
node_modules/@types/core-js/index.d.ts(456,39): error TS2304: Cannot find name 'Promise'.
node_modules/@types/core-js/index.d.ts(464,59): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(465,59): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(467,48): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(468,69): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(472,40): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(474,48): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(494,55): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(495,45): error TS2304: Cannot find name 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(511,46): error TS2304: Cannot find name 'Iterable'.
node_modules/@types/core-js/index.d.ts(512,43): error TS2304: Cannot find name 'Iterable'.
node_modules/@types/core-js/index.d.ts(627,18): error TS2304: Cannot find name 'PromiseConstructor'.
node_modules/@types/core-js/index.d.ts(642,32): error TS2304: Cannot find name 'Iterable'.
node_modules/@types/core-js/index.d.ts(646,39): error TS2304: Cannot find name 'Iterable'.
node_modules/@types/core-js/index.d.ts(646,53): error TS2304: Cannot find name 'Iterator'.
node_modules/@types/core-js/index.d.ts(657,35): error TS2304: Cannot find name 'Promise'.
node_modules/@types/core-js/index.d.ts(1280,34): error TS2339: Property 'for' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1284,41): error TS2339: Property 'hasInstance' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1288,48): error TS2339: Property 'isConcatSpreadable' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1292,38): error TS2339: Property 'iterator' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1296,36): error TS2339: Property 'keyFor' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1300,35): error TS2339: Property 'match' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1304,37): error TS2339: Property 'replace' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1308,36): error TS2339: Property 'search' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1312,37): error TS2339: Property 'species' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1316,35): error TS2339: Property 'split' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1320,41): error TS2339: Property 'toPrimitive' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1324,41): error TS2339: Property 'toStringTag' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(1328,41): error TS2339: Property 'unscopables' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2059,34): error TS2339: Property 'for' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2063,41): error TS2339: Property 'hasInstance' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2067,48): error TS2339: Property 'isConcatSpreadable' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2071,38): error TS2339: Property 'iterator' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2075,36): error TS2339: Property 'keyFor' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2079,35): error TS2339: Property 'match' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2083,37): error TS2339: Property 'replace' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2087,36): error TS2339: Property 'search' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2091,37): error TS2339: Property 'species' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2095,35): error TS2339: Property 'split' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2099,41): error TS2339: Property 'toPrimitive' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2103,41): error TS2339: Property 'toStringTag' does not exist on type 'SymbolConstructor'.
node_modules/@types/core-js/index.d.ts(2107,41): error TS2339: Property 'unscopables' does not exist on type 'SymbolConstructor'.
node_modules/rxjs/Observable.d.ts(68,60): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/Observable.d.ts(68,70): error TS2304: Cannot find name 'Promise'.

npm ERR! Linux 4.4.0-66-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v7.4.0
npm ERR! npm  v4.0.5
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `tsc && concurrently "tsc -w" "lite-server" `
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the [email protected] start script 'tsc && concurrently "tsc -w" "lite-server" '.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the product-management package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     tsc && concurrently "tsc -w" "lite-server" 
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs product-management
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls product-management
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/jabellota/Escritorio/Angular2-ReactiveForms-master/APM/npm-debug.log

I also attach the npm-debug.log file, npm-debug.log.

Unit Tests

Hello Deborah, thanks for putting this course together on pluralsight! It would be a great companion to include unit testing for this demo and would really complete this demo from start to finish. Would love to see some unit testing especially for the product-edit.component.

Thanks!

Create a Form component and an Array Component #2

You created the Address inside the Form, but it would be great to create the one Address component that could be added inside the form.
And it could be even better to create one AddressArray component using the previous Address component.

this way would be very transparent to use one address, or to use the array when it's necessary

I created an example using your code, but it doesn't work perfect yet.
src.zip

Best Online Content Presenter

thank you for your detailed and profound Online courses on Angular (Routing, Reactvie Forms)

Suggestion: You should publish your courses also on Udemy.com.
Here you can with your excellent Presenter Style easy get 1000 subscribers (reactive subscribers :-) ) each valid more than 20$!

kind regards
Hans

Cannot find control with path: angular2

I m getting below error when converting formarray of formgroups to html view.

Cannot find control with path: 'categories -> 0'

ts file
private categories : any= [{name: 'Strict',selected : false},
{name: 'Moderate',selected : true},
{name: 'Flexible',selected : true}];

let allCategories: FormArray = new FormArray([]);
for (let i = 0; i < this.categories.length; i++) {
let fg = new FormGroup({});
fg.addControl(this.categories[i].name, new FormControl(this.categories[i].selected))
allCategories.push(fg)
}

form initialization
categories: allCategories,

Html part

{{category.name}}

Thanks in advance

FormArray controls not accessable inside the FormBuilder

the problem is form array controls(ac, parking) is not visible in templates others controls like(id, name, price...address) working fine.Only problem with amenities FormArray controls. What i am doing wrong here.
hodel.model.ts file

import { AmenitiesModel } from "./amenities.model";
export class HotelModel {
  constructor(public id:number, public name:string, public imagePath:string, public price: number, public description:string,
              public city:string, public address:string, public amenities:AmenitiesModel[]){}

hotel.edit.component.ts file

import { Component, OnInit } from '@angular/core';
import {FormArray, FormBuilder, FormControl, FormGroup} from "@angular/forms";
import { HotelService} from "../hotel.service";
import {ActivatedRoute, Params, Router} from "@angular/router";
import { HotelModel } from "../hotel.model";

@Component({
  selector: 'app-hotel-edit',
  templateUrl: './hotel-edit.component.html',
  styleUrls: ['./hotel-edit.component.css']
})
export class HotelEditComponent implements OnInit {
  hotelEditForm:FormGroup;
  editMode;
  id:number;
  hotel:HotelModel;

  constructor(
              private fb: FormBuilder,
              private hotelService:HotelService,
              private route:ActivatedRoute,
              private router:Router,

              ) { }

  ngOnInit() {
    this.route.params.subscribe(
      (params: Params) => {
        this.id = +params['id'];
        this.editMode = params['id'] != null;
        this.initHotelForm()
    }
    );
    this.hotelEditForm = this.fb.group({
    id:[''],
    name:[''],
    price:[''],
    imagePath:[''],
    description:[''],
    city:[''],
    address:[''],
    amenities:new FormArray([])
  })
  }

  private initHotelForm(){
    let hotelId:number=null;
    let hotelName = '';
    let hotelPrice:number=null;
    let hotelImagePath = '';
    let hotelDescription = '';
    let hotelCity = '';
    let hotelAddress = '';
    let hotelAmenities = new FormArray([]);

    if(this.editMode){
       this.hotelService.getHotel(this.id).subscribe(data => {
         const hotel = data;
         hotelId = hotel.id;
         hotelName = hotel.name;
         hotelPrice = hotel.price;
         hotelImagePath = hotel.imagePath;
         hotelDescription = hotel.description;
         hotelCity = hotel.city;
         hotelAddress = hotel.address;
         if (hotel['amenities']) {
            for (let amenitie of hotel.amenities) {
                hotelAmenities.push(
                  new FormGroup({
                    ac: new FormControl(amenitie.ac),
                    'parking': new FormControl(amenitie.parking)
                  }))
            }}
       this.hotelEditForm.controls['id'].setValue(hotelId);
       this.hotelEditForm.controls['name'].setValue(hotelName);
       this.hotelEditForm.controls['imagePath'].setValue(hotelImagePath);
       this.hotelEditForm.controls['price'].setValue(hotelPrice);
       this.hotelEditForm.controls['description'].setValue(hotelDescription);
       this.hotelEditForm.controls['address'].setValue(hotelCity);
       this.hotelEditForm.controls['address'].setValue(hotelAddress);
       this.hotelEditForm.controls['amenities'].setValue(hotelAmenities);
      });
    }
  }

  getControls() {
  return (<FormArray>this.hotelEditForm.get('amenities')).controls;
  }
  save(){
    if(this.editMode){
      this.hotelService.updateHotel(this.id, this.hotelEditForm.value).subscribe(()=>
        this.router.navigate(['/hotels'], { relativeTo: this.route })
      )
    }
    else{
      this.hotelService.addHotel(this.hotelEditForm.value).subscribe(()=>
        this.router.navigate(['/hotels'], { relativeTo: this.route })
      )
    }
  }
}

Html file to show these array controls

<div class="row">
        <div class="col-xs-12" formArrayName="amenities">
          <div class="row" *ngFor="let amenitieCtrl of getControls(); let i = index" [formGroupName]="i" style="margin-top: 10px">
            <div class="col-xs-8"><input type="text" class="form-control" formControlName="ac">
            </div>


           <div class="col-xs-2"> ppppppppppppppppppppppppppppppppppppppppp
              <input type="text" class="form-control" formControlName="parking">
           </div>
          </div>
        </div>

generic validator and dynamic elements

Hi @DeborahK the genericValidator looks super cool, and I was keen to use this. However while doing a deep dive in the code, I noticed that you subscribe in an ngAfterViewInit method, and in it we fetch all the controls using a @ViewChildren to get the form elements and also subscribe to their Blur Events observable.

If we now have a Form Array and are adding extra tags, then as the component class is already created, our formInputElements will not get updated, and we will not be doing any validation on the newly added Form Controls, and so they will miss out on being validated by the genericValidator.

It may be possible to unsubscribe and then resubscribe each time you add a control, but this didn't feel ideal either.

Anyhow, this may be a possible gotcha, and therefore perhaps worth pointing out in the Read Me.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.