I was trying to add post for a college project but somehow it reloads the page and resets the page. It does not show the post. I tried to submit the form through the add post but it doesn't work.
I'm fairly new to angular so i don't know what to do. Please help me
this is my post.component.html
<h3>Add Post</h3>
<form (formGroup)="form" (ngSubmit)="submit()">
<div class="form-group">
<label for="title">Title</label>
<input
formControlName="title"
id="title"
type="text"
(ngModel)="posts.title"
class="form-control"
required/>
</div>
<div class="form-group">
<label for="body">Body</label>
<input
formControlName="body"
id="body"
type="text"
(ngModel)="posts.body"
class="form-control"
required/>
</div>
<div class="form-group">
<button
class="btn btn-primary"
type="submit">Add Posts</button>
</div>
</form>
this is my post.component.ts for reference
import { Component, OnInit } from '#angular/core';
import { Post } from './post.model';
import { PostService } from './post.service';
import { FormGroup } from '#angular/forms'
import { ActivatedRoute, Router } from '#angular/router';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit, OnDestroy {
id: number;
form: FormGroup;
posts: Post;
post: Post[] = [];
constructor(
public postService: PostService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit(): void {
this.postService.getAll().subscribe((data: Post[])=>{
this.post = data;
console.log(this.post);
})
}
submit(){
console.log(this.form.value);
this.postService.update(this.id, this.form.value).subscribe(res => {
console.log('Post updated successfully!');
})
}
}
don't use reactive form and template driven from same time.
Which means if you are using formControlName don't use ngModel or vice versa.
<h3>Add Post</h3>
<form>
<div class="form-group">
<label for="title">Title</label>
<input
id="title"
type="text"
name="title"
[(ngModel)]="posts.title"
class="form-control"
required/>
</div>
<div class="form-group">
<label for="body">Body</label>
<input
id="body"
type="text"
name="body"
[(ngModel)]="posts.body"
class="form-control"
required/>
</div>
<div class="form-group">
<button
class="btn btn-primary"
type="button" (click)="submit()">Add Posts</button>
</div>
</form>
import { Component, OnInit, VERSION } from '#angular/core';
import { FormGroup } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
id: number;
form: FormGroup;
posts = { title: '', body: ''};
post = [];
constructor(
public postService: PostService,
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit(): void {
this.postService.getAll().subscribe((data)=>{
this.post = data;
console.log(this.post);
})
}
submit(){
console.log(this.posts);
this.postService.update(this.id, this.posts).subscribe(res => {
console.log('Post updated successfully!');
})
}
}
Please follow the changes made in below link. Here I have used template driven form.
https://stackblitz.com/edit/angular-ivy-nnphce?file=src%2Fapp%2Fapp.component.html
Related
API works fine on postman, but shows post 403 error on running the application. I am guessing the error is on the UI side. Please help me correct this!
I'm sharing the screenshots of the headers and response page of network
Headers section
Response section
Here's the relevant code
entry.service.ts
{
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
const AUTH_API = 'http://localhost:8080/Disaster-Analysis-0.0.1-SNAPSHOT%20(5)/';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable({
providedIn: 'root'
})
export class EntryService {
constructor(private http: HttpClient) { }
public getEntry() {
return this.http.get(AUTH_API + 'oldEntry', httpOptions);
}
public addEntry(entry:any) {
return this.http.post(AUTH_API + 'newEntry',entry, httpOptions);
}}
add-entry.component.ts
{
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup } from '#angular/forms';
import { EntryService } from '../_services/entry.service';
#Component({
selector: 'app-add-entry',
templateUrl: './add-entry.component.html',
styleUrls: ['./add-entry.component.css']
})
export class AddEntryComponent implements OnInit {
alert = false;
addNewEntry = new FormGroup({
pincode: new FormControl(''),
majorDamageInSubdivision_A: new FormControl(''),
minorDamageInSubdivision_A: new FormControl(''),
majorDamageInSubdivision_B: new FormControl(''),
minorDamageInSubdivision_B: new FormControl('')
})
constructor(private entry: EntryService) { }
ngOnInit(): void {
}
createEntry() {
this.alert = true;
// this.addEntry.reset()
this.entry.addEntry(this.addNewEntry.value).subscribe((result: any) => {
console.log("Get data from service", result)
})
console.log(this.addNewEntry.value);
}
closeAlert() {
this.alert = false;
}
}
add-entry.component.html
{
<div class="jumbotron">
<h3 class='text-center' >Add Entries Form</h3>
</div>
<div *ngIf="alert" class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Success!</strong> Data added successfully!
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<form [formGroup]="addNewEntry" (ngSubmit)="createEntry()">
<div class="form-group">
<label >Pincode</label>
<input type="text" class="form-control" placeholder="Enter Pincode" formControlName="pincode">
<br>
<label>Major Damage Score in Subdivision A</label>
<input type="text" class="form-control" formControlName="majorDamageInSubdivision_A">
<br>
<label>Minor Damage Score in Subdivision A</label>
<input type="text" class="form-control" formControlName="minorDamageInSubdivision_A">
<br>
<label>Major Damage Score in Subdivision B</label>
<input type="text" class="form-control" formControlName="majorDamageInSubdivision_B">
<br>
<label>Minor Damage Score in Subdivision B</label>
<input type="text" class="form-control" formControlName="minorDamageInSubdivision_B">
<br>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
}
I am a getting the following error on my console even when my paramters match the parameters in the database:- compiler.js:2175 Uncaught Error: Can't resolve all parameters for ClientService: (?).
client.service.ts:
import { Injectable } from '#angular/core';
import {HttpClient} from '#angular/common/http';
import {Observable} from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class Client {
id: number;
firstName: string;
lastName: string;
emailId: string;
constructor()
constructor(id?: number, firstname?: string, lastname?: string, email?: string) {
this.id = id;
this.firstName = firstname;
this.lastName = lastname;
this.emailId = email;
}
}
export class ClientService {
constructor(private http: HttpClient) { }
saveClient(client: Client): Observable<Client> {
return this.http.post<Client>('http://localhost:9091/clients', client); }}
ajout-clients.component.ts
import {Component, forwardRef, Inject, OnInit} from '#angular/core';
import {Client, ClientService} from '../client.service';
#Component({
selector: 'app-ajout-client',
templateUrl: './ajout-client.component.html',
styleUrls: ['./ajout-client.component.css']
})
export class AjoutClientComponent implements OnInit {
constructor(#Inject(ClientService) private clientService:ClientService)
{this.clientService=clientService; }
client: Client = new Client();
submitted = false;
ngOnInit() {
}
newClient(): void {
this.submitted = false;
this.client = new Client();
}
save() {
this.clientService.saveClient(this.client)
.subscribe(data => console.log(data), error => console.log(error));
this.client = new Client();
}
}
the ajout-client.component.html
<h3>Create Client</h3>
<div [hidden]="submitted" style="width: 400px;">
<form (ngSubmit)="onSubmit()">
<div class="form-group">
<label >First Name</label>
<input type="text" class="form-control" id="firstName" required [(ngModel)]="client.firstName"
name="firstName">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" id="lastName" required [(ngModel)]="client.lastName"
name="lastName">
</div>
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" id="emailId" required [(ngModel)]="client.emailId"
name="emailId">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
<div [hidden]="!submitted">
<h4>You submitted successfully!</h4>
<!-- <button class="btn btn-success" (click)="newEmployee()">Add</button> -->
</div>
i keep getting that error i dont know why , any help please
You need to add the #Injectable to your ClientService not to your Client class:
#Injectable()
export class ClientService {}
Otherwise dependency injection does not work
I am working on a angular 7 and following the form.component.html code :
{{ userForm.value | json }}
{{ userModel | json }}
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="userName" [(ngModel)]="userModel.userName">
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" [(ngModel)]="userModel.email">
</div>
<div class="form-group">
<label>Mobile number</label>
<input type="number" class="form-control" name="number" [(ngModel)]="userModel.number">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" name="address" [(ngModel)]="userModel.address">
</div>
<button class="btn btn-primary" type="submit">Submit Order</button>
user.js code
export class User {
constructor(
public userName: string,
public email: string,
public number: string,
public address: string
){}
}
app.component.ts:
import { Component } from '#angular/core';
import { User } from './User';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title=['Angular','Vue','React'];
userModel = new User('ash','ash#gmail.com','01233','asasas');
}
When i compile i get the error "userName" undefined.
<input formControlName="userName" placeholder="Name" class="form-control">
Use this in every input field and it will work.
Change your User class like below
export class User {
public userName: string;
public email: string;
public number: string;
public address: string;
constructor(userName, email, number, address){
this.userName = userName;
this.email = email;
this.number = number;
this.address = address;
}
}
have a look here for more about typescript classes.
as #Hameed Syed said cross check once again for your class import statement.
UPDATED
your code seems fine for me, any how try to use Life Cycle methods from Angular for data binding.
import { Component, OnInit } from '#angular/core';
import { User } from './User';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title=['Angular','Vue','React'];
userModel: User;
ngOnInit(){
this.userModel = new User('ash','ash#gmail.com','01233','asasas');
}
}
I have my form in the app component and my field is coming from the other component with the tag name app-check-form-validation. How shall I validate my form on submit using both the template and the reactive approach. Please help
Home.component.html
<form class="form-horizontal" [formGroup]="registerForm"
(ngSubmit)="onSubmit()">
<div class="form-group">
<div class="col-sm-12">
<app-check-form-validation></app-check-form-validation>
</div>
</div>
<button type="submit" class="btn btn-primary">
Submit
</button>
</form>
Home.component.ts
import { Component, OnInit } from '#angular/core';
import {FormGroup, FormBuilder, Validators, FormControl } from
'#angular/forms';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
});
}
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
}
}
check-form-validation.component.html
<label for="email" class="control-label">Email</label>
<input type="text" id="email" class="form-control" formControlName="email">
<div *ngIf="submitted && registerForm.email.errors" class="invalid-feedback">
<div *ngIf="registerForm.email.errors.required">Email is required</div>
<div *ngIf="registerForm.email.errors.email">Email must be a valid email
address</div>
</div>
check-form-validation.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-check-form-validation',
templateUrl: './check-form-validation.component.html',
styleUrls: ['./check-form-validation.component.css']
})
export class CheckFormValidationComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
You could use a service with an observable. The component which submits could call a service function, while the one which validates could subscribe to the service and take appropriate action.
You can read about services here: https://angular.io/tutorial/toh-pt4
I have a form which allows user to create an account, once the user clicks on submit button the user is navigated to another page with the details of that account they have create. The issue I am having is passing that object to the details view.
For example here is my component for the form,
import {Component, OnInit, OnDestroy, Input} from '#angular/core';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import {Customer} from "../model/customer";
import {Router } from '#angular/router';
import {CustomerService} from "../service/customer.service";
import {CustomerProfileComponent} from "../customer-profile/customer-profile.component";
#Component({
selector: 'app-new-customer',
templateUrl: './new-customer.component.html',
styleUrls: ['./new-customer.component.css']
})
export class NewCustomerComponent implements OnInit {
#Input() customer: Customer;
//this is only dev data do not use this in prod
private countries = [];
private customerSources = [];
private secondarySources =[];
//Create the forum group
public newCustomerForm: FormGroup;
public submitted: boolean; // keep track on whether form is submitted
constructor(private fb: FormBuilder, public customerService: CustomerService,private router: Router) {
this.countries = [
{value:'UK'},
{value:'Germany'},
{value:'Turkey'},
{value:'Italy'}
];
this.customerSources = [
{value: 'Through a friend or colleague (not a Client)'},
{value: 'Through an existing Client'},
{value: 'Direct Sales (e.g. cold call, direct mail, email)'},
{value: 'Web Search e.g. Google'}
];
this.secondarySources = [
{value: '1st Hire'},
{value: 'A Test Client With A Long Business Name'},
{value: 'Abbigail West'}
];
}
ngOnInit() {
this.newCustomerForm = this.fb.group({
id:[''],
company_name: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
vat:[''],
address:[''],
country:[''],
first_name:[''],
surname:[''],
phone:[''],
email:['',[<any>Validators.required, <any>Validators.minLength(5)]],
customer_sources:[''],
secondary_sources:['']
});
}
here is my form html,
<form [formGroup]="newCustomerForm" novalidate (ngSubmit)="saveNewCustomer(newCustomerForm.value, newCustomerForm.valid)">
<section>
<aside>
<p>Once you've added your new <b>Client</b>, you can come back and allow them access to view their <b>Invoices</b> & <b>Payments</b> - they can also make <b>Payments</b> via Paypal if you have it enabled.</p>
</aside>
<input type="hidden" name="id" formControlName="id"/>
<h4>New Client Details</h4>
<md-input-container>
<input mdInput type="text" name="company_name" placeholder="Customer Name" formControlName="company_name" />
<small [hidden]="newCustomerForm.controls.company_name.valid || (newCustomerForm.controls.company_name.pristine && !submitted)">
Customer Name is required (minimum 5 characters).
</small>
</md-input-container>
<md-input-container>
<input mdInput type="text" name="vat" placeholder="VAT Number" formControlName="vat"/>
</md-input-container>
<md-input-container>
<input mdInput type="text" name="address" placeholder="Address" formControlName="address" />
</md-input-container>
<md-select placeholder="Country" name="country" formControlName="country" >
<md-option *ngFor="let country of countries" [value]="country.value" >
{{country.value}}
</md-option>
</md-select>
<h4>Your Primary Contact</h4>
<div class="left-column">
<md-input-container>
<input mdInput type="text" name="first_name" placeholder="First Name" formControlName="first_name" />
</md-input-container>
</div>
<div class="left-column">
<md-input-container>
<input mdInput type="text" name="surname" placeholder="surname" formControlName="surname" />
</md-input-container>
</div>
<div class="clearfix"></div>
<div class="left-column">
<div class="left-column">
<md-input-container>
<input mdInput type="text" name="phone" placeholder="Phone" formControlName="phone"/>
</md-input-container>
</div>
</div>
<div class="right-column">
<div class="left-column">
<md-input-container>
<input mdInput type="text" name="email" placeholder="Email" formControlName="email"/>
<small [hidden]="newCustomerForm.controls.email.valid || (newCustomerForm.controls.email.pristine && !submitted)">
Email is required (minimum 5 characters).
</small>
</md-input-container>
</div>
</div>
<div class="clearfix"></div>
<h4>Customer Source</h4>
<div class="left-column">
<md-select placeholder="How were you introduced to this Client?" formControlName="customer_sources">
<md-option *ngFor="let cs of customerSources" [value]="cs.value" >
{{cs.value}}
</md-option>
</md-select>
</div>
<div class="right-column">
<md-select placeholder="Which Client introduced you?" formControlName="secondary_sources">
<md-option *ngFor="let ss of secondarySources" [value]="ss.value" >
{{ss.value}}
</md-option>
</md-select>
</div>
<div class="clearfix"></div>
</section>
<aside>
<div class="right-aside">
<button type="submit" class="cancel">Cancel</button>
<button type="submit" class="save">Save</button>
</div>
<div class="clearfix"></div>
</aside>
</form>
Customer service is in my app.module. Here I am saving the data and moving the user on to the new page.
saveNewCustomer(customer: Customer, isValid: boolean){
if(isValid){
this.submitted = true; // set form submit to true
this.customerService.saveNewCustomer(customer)
.subscribe(
res => this.customer,
error => console.log(<any>error)
);
this.router.navigateByUrl('/earning/customers/profile');
}
}
}
And this is the component I would like the customer object to use so it be present in the view.
import {Component, OnInit, Input} from '#angular/core';
import {Customer} from "../model/customer";
import {NewCustomerComponent} from "../new-customer/new-customer.component";
#Component({
selector: 'app-customer-profile',
templateUrl: './customer-profile.component.html',
styleUrls: ['./customer-profile.component.css'],
providers:[NewCustomerComponent]
})
export class CustomerProfileComponent implements OnInit {
#Input() customer: Customer;
constructor() {
console.log(this.customer);
}
ngOnInit() {
}
}
<main>
<header>
<h4> </h4>
<h1><strong><i></i>Customer profile</strong></h1>
</header>
<article>
<section>
<p></p>
<p>
{{customer}}
</p>
</section>
</article>
</main>
But customer is undefined in the CustomerProfileComponent. I am not sure what I am doing wrong. if anyone can point me in the right direction would be much appreciated.
Update to include service class based on suggestion
import { Injectable } from '#angular/core';
import {Http, Response, Headers, RequestOptions} from '#angular/http';
import {CookieService} from "angular2-cookie/services/cookies.service";
import {Observable, Subject} from "rxjs";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Customer} from "../model/customer";
#Injectable()
export class CustomerService {
private csrfToken;
private newCustomerUrl = "/earning/customers/new";
private customer = new Subject<Object>();
customer$ = this.customer.asObservable();
constructor(public http: Http, private cookieService: CookieService) {
this.getCsrfToken();
}
getCsrfToken(){
this.csrfToken = this.cookieService.get("PLAY_SESSION").substring(this.cookieService.get("PLAY_SESSION").indexOf("csrfToken"));
}
saveNewCustomer(customer:Customer): Observable<Customer>{
let headers = new Headers({
'Content-Type':'application/json'
});
let options = new RequestOptions({ headers: headers });
return this.http.post(this.newCustomerUrl+"?"+this.csrfToken, customer, options) // ...using post request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch(this.handleError); //...errors if any
}
private handleError (error: Response) {
return Observable.throw('Internal server error: ' + error);
}
emitCustomer(customer) {
this.customer.next(customer);
}
}
As mentioned a shared service would be a good option. the following example is sharing the Object between the components via service:
Your service:
public sharedCustomer = {};
And the component, after that you have received your customer from the api, push the customer to the service:
this.customerService.saveNewCustomer(customer)
.subscribe(res => {
this.customer = res;
this.customerService.sharedCustomer = this.customer;
this.router.navigateByUrl('/earning/customers/profile');
});
}
Notice that I'm emitting the customer inside the subscription, as well as the navigation, to ensure that the customer gets stored in the service properly, as well as not navigating away from page before that.
Then in your detail page:
ngOnInit() {
this.customer = this.customerService.sharedCustomer;
}