Cannot find control error,Unable to upload image from angular 2 - html

I am trying to upload image but i am getting the error
Here is my template
<h3 class = "head">{{title}}</h3>
<form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
<div class="row">
<div class="form-group">
<label class="formHeading">firstname</label>
<input type="text" id="facebook" class="form-control" ngControl="firstname" #firstname="ngForm" >
</div>
<div *ngIf ="firstname.touched">
<div *ngIf ="!firstname.valid" class = "alert alert-danger">
<strong>First name is required</strong>
</div>
</div>
<div class="form-group">
<label class="formHeading">lastname</label>
<input type="text" id="facebook" class="form-control col-xs-3" ngControl="lastname" #lastname="ngForm" >
</div>
<div *ngIf ="lastname.touched" >
<div *ngIf = "!lastname.valid" class = "alert alert-danger">
<strong>Google name is required</strong>
</div>
</div>
<div class="form-group">
<label class="formHeading">image</label>
<input type="file" id="facebook" class="form-control col-xs-3" ngControl="image" #image="ngForm" >
</div>
<div class="form-row btn">
<button type="submit" class="btn btn-primary pull-right butspace " [disabled]="!form.valid">Save</button>
</div>
</div>
my Component
import {Component} from '#angular/core';
import {Http, Response, Headers} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject } from 'rxjs/Subject';
import {FORM_DIRECTIVES} from '#angular/common';
import {Control,FormBuilder,ControlGroup,Validators} from '#angular/common';
#Component({
templateUrl: './components/profile/profile.html',
directives: [FORM_DIRECTIVES],})
export class Profile {
http: Http;
form: ControlGroup;
postResponse = new Person();
constructor(fbld: FormBuilder,http: Http) {
this.http = http;
this.form = fbld .group({
firstname: ['', Validators.required],
lastname: ['', Validators.required]
});
}
onSubmit(form){
//this.form = form;
console.log(form);
var headers = new Headers();
// headers.append('Content-Type', 'application/json');
headers.append('Content-Type','application/x-www-form-urlencoded') this.http.post('http://localhost/angular/index.php/profile/addprofile', JSON.stringify(form),{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.postResponse = res);
}
}
class Person{
firstName:string;
lastName:string;
}
It shows the error "Cannot find control 'image' in html file" and i am not able to find the exact issue can someone suggest the error in my code.

I believe the issue is that you have ngControl="image" on one of your inputs, but you never officially made image part of the form in FormBuilder. ngControl is looking for image on the form (to initialize the value), but it can't find it.
Try adding image to this:
this.form = fbld .group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
image: ['', Validators.required]
});
And maybe here too:
class Person{
firstName:string;
lastName:string;
image: any;
}
Not sure what the data type is for your image, but this is a start.

Related

Angular#13 formGroup values are null (reactive forms)

Been trying to access form instance values bt they are all null..It worked fine in tempalate driven forms. I have imported ReactiveFormsModule. I have played around with the attr but I cant find what am missing??
The form is invalid the moment I use Validators.required meaning its empty
.component.html
<form [formGroup] ="tryForm" (ngSubmit)="onSubmit()" >
<div class="form-group">
<label>Name</label><br>
<input type="text" FormControlName ="name">
<span *ngIf="tryForm.invalid">Name required</span>
</div>
<!-- <div *ngIf="name.invalid" class="alert alert-danger"></div> -->
<div class="form-group">
<label>Email</label><br>
<input type="text" FormControlName ="email">
</div>
<div class="form-group">
<label>Message</label><br>
<input type="text" FormControlName ="message">
</div>
<button type = "submit" >Submit</button>
</form>
.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormControl,FormGroup,Validators} from '#angular/forms';
import { Router} from '#angular/router'
#Component({
selector: 'app-log-in',
templateUrl: './log-in.component.html',
styleUrls: ['./log-in.component.css']
})
export class LogInComponent implements OnInit {
tryForm = this.fb.group({
name : [''],
email: [''],
message: [''],
});
constructor(private fb:FormBuilder,
private router: Router) { }
onSubmit(){
if (this.tryForm.status == "VALID"){
alert("Form Submitted Successfully.")
alert(this.tryForm.get("name")?.value);
this.tryForm.reset();
first you need to change the html FormControlName to formControlName. you can read the full explanation here.
HTML
<form [formGroup]="tryForm" (ngSubmit)="onSubmit(tryForm.value)">
<div class="form-group">
<label>Name</label><br />
<input type="text" formControlName="name" />
<span *ngIf="tryForm.invalid">Name required</span>
</div>
<div class="form-group">
<label>Email</label><br />
<input type="text" formControlName="email" />
</div>
<div class="form-group">
<label>Message</label><br />
<input type="text" formControlName="message" />
</div>
<button type="submit">Submit</button>
</form>
after that change your ts like bellow, make sure you initialize the form on ngOnInit.
TS
export class LogInComponent implements OnInit {
tryForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.createForm();
}
createForm() {
this.tryForm = this.fb.group({
name : [''],
email : [''],
message: [''],
});
}
onSubmit(data) {
console.log(data);
}
}
I replicate your code here
change this <input type="text" FormControlName ="email"> to this;
<input type="text" formControlName="email">
and build your form on ngOnInit,
ngOnInit(){
this.tryForm = this.fb.group({
name : [''],
email: [''],
message: [''],
});
}

Reactive form email validation in angular 7

I am new in angular.Email validation is not working in my reactive form validation. I have an error somewhere, but I'm not sure what it is.
Script:
this.loginForm = this.formBulder.group({
fname:['', Validators.required],
lname:['', Validators.required],
email:['', Validators.required],
password:['', Validators.required,Validators.maxLength(5)],
retypepassword:['', Validators.required,Validators.maxLength(5)]
});
https://stackblitz.com/edit/angular-forms-validation-tfzhug?file=app/app.component.html
try to this way
const emailPattern = '[a-zA-Z0-9.-_]{1,}#[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,63}';
mail = new FormControl('',Validators.compose( [Validators.required,Validators.pattern(emailPattern)]));
ts code
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder, Validators} from '#angular/forms';
import { UserService } from '../../shared/services/user.service';
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
#Component({
selector: 'forget-password',
templateUrl: './forget-password.component.html',
styleUrls: ['./forget-password.component.css']
})
export class ForgetPasswordComponent implements OnInit {
form: FormGroup = new FormGroup({});
errors:any;
failed:boolean=false;
success:boolean=false;
constructor(private userService: UserService,private fb: FormBuilder) {
this.form = this.fb.group({
email: ['', [Validators.required, Validators.email, Validators.pattern(EMAIL_REGEX)]]
});
}
ngOnInit() {
}
get f() {
return this.form.controls;
}
isFieldValid(field: string) {
return (
(this.form.get(field).touched ||
this.form.get(field).untouched) && this.form.get(field).valid
);
}
forgetPassword() {
this.failed=false;
this.success=false;
this.userService.forgetPassword(this.form.value).subscribe(result=>{
this.success=true;
this.form.reset();
},errors=>{
this.failed=true;
this.errors=errors;
})
}
}
View
<form [formGroup]="form" (ngSubmit)="forgetPassword()">
<div class="md-form form-sm mb-2">
<i class="fa fa-envelope prefix"></i>
<input type="text" class="form-control" formControlName="email" type="email"
placeholder="Enter Your Email Address">
<div *ngIf="f.email.touched && f.email.invalid" class="text-danger">
<div *ngIf="f.email.errors.required">Email is required.</div>
<div *ngIf="f.email.errors.email">Email must be a valid email address</div>
</div>
</div>
<div class="text-center mt-2">
<button class="btn btn-primary" type="submit" [disabled]="!form.valid">Send Password Reset Email
<i class="fa fa-sign-in ml-1"></i>
</button>
</div>
<div *ngIf="failed" class="text-danger" role="alert">
<strong>Oops! </strong> <span *ngFor="let error of errors">{{error}}</span>
</div>
<div *ngIf="success" class="alert alert-success" role="alert">
Successfully change your password
</div>
</form>
you can try this :
this.loginForm = this.formBulder.group({
'fname': new FormControl('',Validators.required),
'lname': new FormControl('',Validators.required),
'email': new FormControl('',[Validators.required,Validators.email]),
'password': new FormControl('',[Validators.required,Validators.maxLength(5)]),
'retypepassword': new FormControl('',[Validators.required,Validators.maxLength(5)]),
});

Angular - Form validation without form tag

I'm trying to finalise a register form. I've to do it without using the form tag.
I've this registerform:
<div class="row">
<div class="center col-xs-8 col-xs-offset-2">
<p class="h5 text-center mb-4">{{ 'Signup' | translate }}</p>
<div class="form-group">
<label for="email">{{ 'SignupEmail' | translate }}</label>
<input type="text" [(ngModel)]="user.email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">Email must be a valid email address</div>
</div>
</div>
<div class="form-group">
<label for="username">{{ 'SignupUsername' | translate }}</label>
<input type="text" [(ngModel)]="user.name" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
</div>
<div class="form-group">
<label for="password">{{ 'SignupPassword' | translate }}</label>
<input type="password" [(ngModel)]="user.password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
</div>
<div class="form-group">
<label for="birth">{{ 'SignupBirth' | translate }}</label>
<input type="date" [(ngModel)]="user.dateNaissance" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
</div>
<div class="form-group">
<button [disabled]="loading" class="btn btn-info" (click)="onSubmit()" >{{ 'SignupSubmit' | translate }}</button>
<img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
<div class="text-center">
{{ 'SignupAccount1' | translate }} <a routerLink="/login">{{ 'SignupAccount2' | translate }}</a>
</div>
</div>
</div>
</div>
The problem, is that the mail and the other input are always required even if i put a correct address mail in the input. And i don't get why...
Here is the register.component.ts
import {Component, OnInit} from '#angular/core';
import {FormGroup, FormBuilder, Validators} from '#angular/forms';
import {first} from 'rxjs/operators';
import {Router} from '#angular/router';
import {AlertService} from '../services/alert.service';
import {UserService} from '../services/user.service';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.sass']
})
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
loading = false;
submitted = false;
user: any;
constructor(private fb: FormBuilder, private router: Router, private userService: UserService, private alertService: AlertService) {
}
ngOnInit() {
this.registerForm = this.fb.group({
username: ['', Validators.required],
//gender: ['', Validators.required],
birth: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]]
});
this.user = new Object();
}
click(ev) {
console.log(ev.target.defaultValue);
}
// convenience getter for easy access to form fields
get f() {return this.registerForm.controls;}
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
window.alert("Informations invalides");
return;
}
this.loading = true;
this.userService.register(this.registerForm.value)
.pipe(first())
.subscribe(
data => {
this.alertService.success('Registration successful', true);
this.router.navigate(['/login']);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
}
Can you help me validate this form (but without adding the form tag)...
Thank you !
You had used reactive form, So use [formGroup] in div and inside that div use formControlName to achieve validation.
Here i have created one reactive form demo with validation and without form tag.
Stackblitz Demo without Form Tag

write value from input to firebase using typescript

I'm new to Angular and Typescript. I'm trying to figure out how to get a value from an input to firebase using AngularJS and Typescript. I've been following many tutorials but i cant seem to get this working unless i hard-code the values.
Here is my HTML;
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-body">
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<!--Form Starts Here-->
<div class="form-group col-xs-12">
<div id="nameOfProp" class="form-group">
<label for="nameOfProp">1. Name of Proposal:</label>
<input
class="form-control"
id="nameOfPropInput"
name="nameOfProp"
placeholder="Name of Proposal"
type="text"
ngModel
required
#nameOfProp
/>
</div>
</div>
<div class="form-group col-xs-12">
<div id="tradingAs" class="form-group">
<label for="tradingAs">Trading as:</label>
<input
class="form-control"
id="tradingAsInput"
name="tradingAs"
placeholder="Trading as..."
style="margin-bottom: 5px"
type="text"
ngModel
required
/>
</div>
</div>
<div class="row">
<div class="form-group">
<button
class="btn btn-primary"
type="submit"
[disabled]="!f.valid "
required
>Submit</button>
</form>
</div>
</div>
</div>
here is my component;
import {Component, OnInit, ViewChild} from '#angular/core';
import {FormGroup, NgForm} from '#angular/forms';
import {Router} from '#angular/router';
import {GplService} from '../../gpl.service';
import {OneData} from './onedata.model';
#Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.css']
})
export class OneComponent /*implements OnInit*/ {
// oneData: OneData[] = [
// new OneData('', 'Test One')
// ];
oneData: OneData[] = [
new OneData('nameOfProp', 'tradingAs')
];
constructor(private gplService: GplService) {}
onSubmit(form: NgForm) {
console.log(form);
this.gplService.storeGpl(this.oneData)
.subscribe(
(response) => console.log(response),
(error) => console.log(error)
);
}
}
Not sure if this is correct but i tried to create a data model as well;
export class OneData {
public nameOfProp: string;
public tradingAs: string;
constructor(nameOfProp: string, tradingAs: string) {
this.nameOfProp = nameOfProp;
this.tradingAs = tradingAs;
}
}
gpl service to connect to firebase and post;
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
#Injectable()
export class GplService {
constructor(private http: Http) {}
storeGpl(oneData: any []) {
return this.http.post('https://satibgpl.firebaseio.com/gpldata.json', oneData);
}
}
Again, i need to know how to pass values from in my html to the component instead of hardcoding it.
Thank you guys.

http in angular 2,unable to add records to database

I am trying to post the form data to my database using Angular2 but only the null values are inserted to my database.I am new to angular can someone find the error in my code
My template,
<form (ngSubmit)="onSubmit()" [(ngFormModel)]="form" #f="ngForm">
<div class="form-row">
<div class="formHeading">Facebook</div>
<input type="text" id="fb" ngControl="facebook">
<div class="errorMessage" *ngIf="f.form.controls.fb.touched && !f.form.controls.fb.valid"> Facebook address is required</div>
</div>
<div class="form-row">
<div class="formHeading">Google</div>
<input type="text" id="gl" ngControl="google" >
<div class="errorMessage" *ngIf="f.form.controls.gl.touched && !f.form.controls.gl.valid">Google address is required</div>
</div>
<div class="form-row">
<div class="formHeading">Twitter</div>
<input type="text" id="twt" ngModel = f.twitter >
</div>
<div class="form-row">
<div class="formHeading">LinkedIn</div>
<input type="text" id="li" >
</div>
<div class="form-row">
<button type="submit" [disabled]="!f.form.valid">Save</button>
</div>
</form>
My Component
import {Component} from '#angular/core';
import {FormBuilder, Validators, ControlGroup, FORM_DIRECTIVES} from '#angular/common';
import {Http, Response, Headers} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject } from 'rxjs/Subject';
#Component({
selector: 'social-form',
directives:[FORM_DIRECTIVES],
templateUrl: './components/social/social.html',
providers: [FormBuilder]
})
export class Social {
http: Http;
form;
payLoad = null;
constructor(fb: FormBuilder) {
this.form = fb.group({
"fb": ['', Validators.required],
"gl": ['',Validators.required],
});
}
constructor(http: Http) {
this.http = http;
}
onSubmit() {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost/a2server/index.php/profile/addsocial', JSON.stringify({?????????????}),{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.form = res);
}
}
class Person{
facebook:string;
google:string;
twitter:string;
linkedin:string;
}
What should i need to keep in json stringify?
Here i want validations,so i put a constructor similarlly i need http, am i need another constructor?If yes where should i put it since i cannot put two constructors in one component.