ngModel is not binding select in angular 4 - javascript

I have a form in my application which contains title, price, category (select) and imagUrl data. I applied ngModel with every field and it's working fine except the select element. When I console.log() form data I get the value of every field but the value of the select element which is undefined. I imported the AngularForms module in app.module.ts
this is my product-form-component-html code
<form #f="ngForm" (ngSubmit)="save(f.value)" >
<div class="form-group">
<label for="title">Title</label>
<input ngModel name="title" id="title" type="text" class="form-control">
</div>
<div class="form-group">
<label for="price">Price</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input ngModel name="price" id="price" type="number" class="form-control">
</div>
</div>
<div class="form-group">
<label for="category">category</label>
<select ngModel name="category" id="category" class="form-control">
<option value=""></option>
<option *ngFor="let c of categories$ | async" [value]="c.key$">
{{ c.name }}
</option>
</select>
</div>
<div class="form-group">
<label for="imageUrl">image URL</label>
<input ngModel name="iamgeUrl" id="imageUrl" type="text" class="form-control">
</div>
<button class="btn btn-primary">Save</button>
</form>
this is product-form-component.ts file
import { Component, OnInit } from '#angular/core';
import { CategoryService } from '../../category.service';
import { ProductService } from '../../product.service';
#Component({
selector: 'app-product-form',
templateUrl: './product-form.component.html',
styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
categories$;
constructor(categoryService: CategoryService, private productService: ProductService ) {
this.categories$ = categoryService.getCategories();
}
ngOnInit() {
}
save(product) {
console.log(product);
this.productService.create(product);
}
}
this is product-service.ts
import { Injectable } from '#angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
#Injectable()
export class ProductService {
constructor(private db: AngularFireDatabase) { }
create(product) {
return this.db.list('/products').push(product);
}
}
what am I doing wrong? please help me with detailed answer
my Firebase Database

this is the answer [value]="c.$key"
. I was assigning [value]="c.key$" that is why i was getting error.

Related

Prepopulate the existing values in the form field in Angular

I want to update existing data information using update data form. The input should populate the existing values. How to do that?
As of now, I have to enter all the fields manually to update the form.
Update doctor .ts file
import { Component, OnInit } from '#angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
import { Doctor } from '../doctor';
import { DoctorService } from '../doctor.service';
#Component({
selector: 'app-update-doctor',
templateUrl: './update-doctor.component.html',
styleUrls: ['./update-doctor.component.css']
})
export class UpdateDoctorComponent implements OnInit {
id:any;
doctor:Doctor;
updateForm:FormGroup;
constructor(private route: ActivatedRoute, private router: Router,private doctorservice: DoctorService,private formbuilder:FormBuilder) {
}
ngOnInit() {
this.doctor = new Doctor();
}
updateDoctor(){
this.doctorservice.updateDoctor( this.doctor)
.subscribe(data =>{
console.log(data);
this.doctor = new Doctor();
window.location.reload();
})
this.gotoList();
}
onSubmit(){
this.updateDoctor();
}
gotoList() {
this.router.navigate(['doctor']);
}
}
update doctor .html file
<div class="card col-md-4 offset-md-4 mt-3" >
<h3>Update Doctor</h3>
<div style="width: 100% ;">
<form (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="doctorId"> Id</label>
<input type="text" class="form-control" id="doctorId" required [(ngModel)]="doctor.doctorId" name="doctorId" #doctorId>
</div>
<div class="form-group">
<label for="doctorName"> Name</label>
<input type="text" class="form-control" id="doctorName" value="{{doctor.doctorName}}" required [(ngModel)]="doctor.doctorName" name="doctorName" #doctorId>
</div>
<div class="form-group">
<label for="doctorProfile">Profile</label>
<input type="text" class="form-control" id="doctorProfile" required [(ngModel)]="doctor.doctorProfile" name="doctorProfile">
</div>
<div class="form-group">
<label for="doctorSpeciality">Speciality</label>
<input type="text" class="form-control" id="doctorSpeciality" value="{{doctor.doctorSpeciality}}" required [(ngModel)]="doctor.doctorSpeciality" name="doctorSpeciality">
</div>
<div class="form-group">
<label for="doctorQualification">Qualification</label>
<input type="text" class="form-control" id="doctorQualification" value="{{doctor.doctorQualification}}" required [(ngModel)]="doctor.doctorQualification" name="doctorQualification">
</div>
<div class="form-group">
<label for="doctorEmail">Email</label>
<input type="text" class="form-control" id="doctorEmail" value="{{doctor.doctorEmail}}" required [(ngModel)]="doctor.doctorEmail" name="doctorEmail">
</div>
<div class="form-group">
<label for="doctorPassword">Password</label>
<input type="password" class="form-control" id="doctorPassword" required [(ngModel)]="doctor.doctorPassword" name="doctorPassword">
</div>
<button type="submit" class="btn btn-dark">Submit</button>
</form>
</div>
</div>
From this function I am navigating to update doctor form
updateDoctor(){
this.router.navigate(['update'])
}
service method for update.
updateDoctor(doctor:Object):Observable<Object>{
return this.http.put(`${this.baseUrl1}`,doctor);
}
You could write a service to get the existing form data and load the data in the form through this.doctor object on load.

Property 'title' does not exist on type '{}'

Angular
In the first few tags I have an input tag input #title = "ngModel" [(ngModel)]="product.title" this code where I am trying to use two way binding to be able to edit my form and values that I get from the firebase database. I created an empty product object in product-form.component.ts but I get the property type error. I am not sure why the empty product object causing error because the tutorial I'm watching has the same approach. Goal is to be able to use that empty product object or an alternate approach to be able to work with two way binding
product-form.component.ts
import { ProductService } from './../../product.service';
import { CategoryService } from './../../category.service';
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { take } from 'rxjs/operators';
#Component({
selector: 'app-product-form',
templateUrl: './product-form.component.html',
styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
categories$;
product = {};
constructor(
private route: ActivatedRoute,
private router: Router,
private categoryService: CategoryService,
private productService: ProductService)
{
this.categories$ = categoryService.getCategories();
let id = this.route.snapshot.paramMap.get('id');
if (id) this.productService.get(id).pipe(take(1)).subscribe(p => this.product = p);
}
save(product){
this.productService.create(product);
this.router.navigate(['/admin/products']);
}
ngOnInit(): void {
}
}
product-form.html
<div class="row">
<div class="col-md-6">
<form #f = "ngForm" (ngSubmit) = "save(f.value)">
<div class="form-group">
<label for="title">Title</label>
<input #title = "ngModel" [(ngModel)]="product.title" name = "title" id = "title" type="text" class="form-control" required>
<div class="alert alert-danger" *ngIf = "title.touched && title.invalid">
Title is required
</div>
</div>
<div class="form-group">
<label for="price">Price</label>
<div class="input-group">
<span class="input-group-text">$</span>
<input #price="ngModel" ngModel name ="price" id = "price" type="number" class="form-control" required>
</div>
<div class="alert alert-danger" *ngIf="price.touched && price.invalid">
<div *ngIf="price.errors.required">Price is required.</div>
<div *ngIf="price.errors.min">Price should be 0.</div>
</div>
</div>
<div class="form-group">
<label for="category">Category</label>
<select #category="ngModel" ngModel name="category" id = "category" type="text" class="form-control" required>
<option value=""></option>
<option *ngFor = "let c of categories$ | async" [value] = "c.name">
{{c.name}}
</option>
</select>
<div class="alert alert-danger" *ngIf = "category.touched && category.invalid">
Category is required.
</div>
</div>
<div class="form-group">
<label for="imageUrl">Image Url</label>
<input #imageUrl="ngModel" ngModel name= "imageUrl" id = "imageUrl" type="url" class="form-control" required>
<div class="alert alert-danger" *ngIf = "imageUrl.touched && imageUrl.invalid">
<div *ngIf = "imageUrl.errors.required">Image URL is required.</div>
<div *ngIf = "imageUrl.errors.url">Invalid URL</div>
</div>
</div>
<button class="btn btn-primary">Save</button>
</form>
</div>
<div class="col-md-6">
<div class="card" style="width: 18rem;">
<img [src]="imageUrl.value" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{title.value}}</h5>
<p class="card-text">{{price.value | currency:'USD':true}}</p>
</div>
</div>
</div>
</div>
product.service.ts
import { Injectable } from '#angular/core';
import { AngularFireDatabase } from '#angular/fire/database';
#Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private db: AngularFireDatabase) { }
create(product){
return this.db.list('/products').push(product);
// const itemsRef = this.db.list('products');
// return itemsRef.push(product);
}
getAll() {
return this.db.list('/products').valueChanges();
}
get(productId){
return this.db.object('/products/' + productId).valueChanges();
}
}
There are 2 ways to do this
Approach 1
Declare an interface
export interface Product {
title: string
}
Change the Component code section as follows
from
product = {};
To
product:Product;
Approach 2 - This can have side effects
Change HTML
From
<input #title = "ngModel" [(ngModel)]="product.title" name = "title" id = "title" type="text" class="form-control" required>
To
<input #title = "ngModel" [(ngModel)]="product['title']" name = "title" id = "title" type="text" class="form-control" required>
I fixed this error by changing a couple of things in 'tsconfig.json' file.
First remove "strict":true and add instead of it "noImplicitUseStrict":true
(Don't forget adding the comma)

When using template driven forms in Angular 2, how to access the form in the component?

I have a simple template driven form like so:
HTML:
<div class="container">
<h1>Hero Form</h1>
<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" [(ngModel)]="model.name" name="name" #name="ngModel">
</div>
<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input type="text" class="form-control" id="alterEgo" [(ngModel)]="model.alterEgo" name="alterEgo">
</div>
<div class="form-group">
<label for="power">Hero Power</label>
<select class="form-control" id="power" [(ngModel)]="model.power" name="power">
<option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
</select>
</div>
<button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid">Submit</button>
</form>
</div>
Component:
import { Component, OnInit } from '#angular/core';
import { Hero } from './hero';
#Component({
selector: 'at-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.scss']
})
export class HeroComponent implements OnInit {
constructor() {
//
}
ngOnInit() {
//
}
powers = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer'];
model = new Hero(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet');
submitted = false;
onSubmit() { this.submitted = true; }
newHero() {
this.model = new Hero(42, '', '');
}
}
How can I:
Reset the whole form from the component (not from the markup)?
Reset a single form field (e.g. the name field) also from the component and not the markup?
You can get the form by using ViewChild
Markup
<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
...
</form>
Component
#ViewChild('heroForm') public heroForm: NgForm;
I suggest you also to look at Reactive Forms too. I think this will be more handy if you want to work with form in the typescript, not in the markup

Creating an add button for dynamic fields not working

I am trying to create a dynamic field with an add button and a delete button with the Address class. I am stuck as to why the addAddress function does not work. I searched around for a solution but nothing I have searched has worked. I am a novice with Angular so I might be making this more complicated then it needs to be. Here is the app.component.ts
import { FormGroup, FormControl, FormArray, FormBuilder } from
'#angular/forms';
import { Component, OnInit } from '#angular/core';
import { Validators} from '#angular/forms';
class Address{
constructor(public stName, public aptNo, public pinCode){
}
}
class registrationModel{
constructor(public firstName, public lastName,public age,public fromStates,
public state, public homeAddress:Array<Address> ){}
}
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
private _formObject:FormGroup;
private _formModel:registrationModel;
private _addressObject:Address;
private _createFormGroup(){
this._formObject = this._formBuilder.group({
addLabelTitle:["", Validators.minLength(2)],
addLabelType:["", Validators.minLength(2)],
firstName:[],
lastName:[],
age:[18, [Validators.min(18), Validators.max(60)]],
fromStates:[false],
state:[],
stName: [],
aptNo: [],
pinCode: [],
homeAddress:this._formBuilder.array([Address])
});
this._formObject.reset(this._formModel);
console.info(this._formObject);
}
private _submitValue(){
// this._formObject = this._formBuilder.group({
// addLabelTitle:[],
// addLabelType:[],
// firstName:[],
// lastName:[],
// age:[],
// fromStates:[false],
// state:[]
// });
console.info(this._formObject.value);
}
private _resetValue(){
this._formObject.reset();
}
private _addAddress(){
this._addressObject = new Address("","","");
/*
Create a address model.
Inject it to formObject.
*/
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<small>{{this._formObject.value|json}}</small>
<!--The content below is only a placeholder and can be replaced.-->
<div class="registrationForm" [formGroup]="_formObject">
<!-- Name Input box -->
<div class="formGroup">
<label>Name :</label>
<input type="text" placeholder="First Name" formControlName="firstName"
ngModel required>
<input type="text" formControlName="lastName" placeholder="Last Name"
ngModel required>
</div>
<!-- Name Age box -->
<div class="formGroup">
<label>Age :</label>
<input type="number" placeholder="Age" formControlName="age">
<small *ngIf="_formObject.controls.age.errors">
{{getErrors(_formObject.controls.age.errors)}}</small>
</div>
<!-- form United States -->
<div class="formGroup">
<label>From United States </label>
<input type="checkbox" formControlName="fromStates" ngModel required>
</div>
<!-- States -->
<div class="formGroup">
<label>States :</label>
<select formControlName="state">
<option value="co">Colordo</option>
<option value="ca">California</option>
</select>
</div>
<div class="formGroup">
<label>formControlName </label>
<select formControlName="state">
<option value="co">Colordo</option>
<option value="ca">California</option>
</select>
</div>
<hr/>
<div formArrayName="homeAddress">
<button>Delete</button>
<div *ngFor="let address of this._formObject.controls.homeAddress.controls;
let i=index">
<div [formGroupName]="i">
<div class="formGroup">
<label>St Name :</label>
<input type="text" placeholder="" formControlName="stName" ngModel
required>
</div>
<div class="formGroup">
<label>Apt Number :</label>
<input type="text" placeholder="" formControlName="aptNo" ngModel
required>
</div>
<div class="formGroup">
<label>Pincode :</label>
<input type="text" placeholder="" formControlName="pinCode" ngModel
required>
</div>
<!-- <div class="formGroup">
<label>Add Label: </label>
<input type="text" placeholder="Label Title"
formControlName="addLabelTitle">
<input type="text" placeholder="Type (Text, Checkbox, etc)"
formControlName="addLabelType">
</div>
-->
</div>
<hr/>
</div>
<div class="formGroup text-center">
<button (click)="_addAddress()">Add address</button>
<!-- Submit -->
<button (click)="_submitValue()">Submit</button>
<!-- Cancel -->
<button (click)="_resetValue()">Cancel</button>
</div>
</div>
You need to add a formgroup to your form array, if you like to use the class Address you have, you can do it by
_addAddress() {
let formArr = this._formObject.controls.homeAddress;
formArr.push(this._formBuilder.group(new Address('','','')))
}
You can remove all ngModel and required from your form, these belong with template driven forms.
The build of the form is I would create an empty FormArray, and then just call _addAddress after the build of the form since you probably want an initial formgroup in your form array.
As a sidenote, I can't see that the following would even work (?)
homeAddress:this._formBuilder.array([Address])
So I would scrap that and do:
_createFormGroup(){
this._formObject = this._formBuilder.group({
// all other form controls here
homeAddress:this._formBuilder.array([])
});
this._addAddress();
}

Angular 2 error- There is no directive with "exportAs" set to "ngModel" with RC4 version

I am using angular 2 forms in my application and i have created the forms based on given link.
https://angular.io/docs/ts/latest/guide/forms.html
In this for validation and to use forms APIs, i have set the ngModel values like #name="id" #id="ngModel" and which throws script error. But its resolved if i set #id="ngModel" as #id="ngForm". But for my case i have to set my model value to ngModel.
Below is my html page.
<form (ngSubmit)="onSubmit()" #myForm="ngForm">
<div class="form-group">
<label class="control-label" for="id">Employee ID</label>
<input type="text" class="form-control" required [(ngModel)]="model.id" #name="id" #id="ngModel" >
<div [hidden]="id.valid || id.pristine" class="alert alert-danger">
Employee ID is required
</div>
</div>
<div class="form-group">
<label for="name">Employee Name</label>
<input type="text" class="form-control" [(ngModel)]="model.name" name="name" #name="ngModel" required>
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
Employee ID is required
</div>
</div>
<div class="form-group">
<label for="DOJ">DOJ</label>
<input class="form-control" required [(ngModel)]="model.DOJ" name="DOJ" #DOJ="ngModel" />
<div [hidden]="DOJ.valid || DOJ.pristine" class="alert alert-danger">
DOJ is required
</div>
</div>
<button type="submit" class="btn btn-default" [disabled]="!myForm.form.valid">Submit</button>
</form>
Below is my issue.
EXCEPTION: Template parse errors:
There is no directive with "exportAs" set to "ngModel" ("
<div>
<h1>My Form</h1>
<form (ngSubmit)="onSubmit()" [ERROR ->]#myForm="ngModel">
<div class="form-group>
<label class="control-label" for="id">Employee"):AppComponent#3:34
I have checked with more questions and answers, most of them said to update angular2 version to RC4 so i have updated my application to rc4 but still i am facing this issue.
Below is my ts file:
import {Component} from '#angular/core';
import { disableDeprecatedForms, provideForms , NgForm} from '#angular/forms';
import {CORE_DIRECTIVES, FORM_DIRECTIVES, FormBuilder,Validators,Control,ControlGroup } from '#angular/common';
#Component({
selector: 'ej-app',
templateUrl: 'app/app.component.html',
directives: [ CORE_DIRECTIVES,FORM_DIRECTIVES]
})
export class AppComponent {
model = new Employees(null,'','');
onSubmit() { alert("values submitted")}
constructor() {
}
}
export class Employees {
constructor( public id: number,public name: string, public DOJ: String ) { }
}
Do not import the FORM_DIRECTIVES and CORE_DIRECTIVES because they are deprecated, instead make sure that you import the NgForm. You can use the following:
import {FormGroup, FormBuilder, FormControl, Validators, NgForm } from '#angular/forms';
Don't mix the new and old forms module.
import {CORE_DIRECTIVES, FORM_DIRECTIVES, FormBuilder,Validators,Control,ControlGroup } from '#angular/common';
imports forms stuff from #angular/common. If you use the new forms
bootstrap(AppComponent, [disableDeprecatedForms(), provideForms()])
then use instead
import {FORM_DIRECTIVES, FormBuilder,Validators,Control,ControlGroup } from '#angular/forms';

Categories

Resources