Component not rendering on Angular, It shows no error - html

I am trying to upload the product details to which I am trying to get the values from the form.
I always face problem with handling forms with angular. Other components are rendering with no problem.
This is the component.html code:
<form>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control" #title/>
</div>
<div class="form-group">
<label for="category">Category</label>
<select name="category" id="category" class="form-control" #category>
<option value="cardio">Cardio</option>
<option value="strength">Strength</option>
<option value="strength">Cross Training</option>
<option value="strength">Outdoor</option>
<option value="strength">Home equipment</option>
</select>
</div>
<div class="form-group">
<label for="imported">Imported</label>
<select name="category" id="category" class="form-control" #imported>
<option value="International">International</option>
<option value="Indian">Indian</option>
</select>
</div>
<div class="form-group">
<label for="type">Type</label>
<input type="text" name="type" id="type" class="form-control" #type/>
</div>
<div class="form-group">
<label for="description">Description</label>
<input name="description" id="description" class="form-control" #description/>
</div>
<div class="form-group">
<label for="product-img">Image of the product</label>
<input type="file" (change)="onFileChange($event)" class="form-control"/>
</div>
<button type="button" (click)="uploadProduct(title.value, category.value, imported.value, type.value, description.value)" class="button-theme">Submit</button>
</form>
This is the component.ts code,
import { Component, OnInit } from '#angular/core';
import { Product } from '../model/product';
import { ProductsService } from '../products.service';
import { FormControl, FormGroup } from '#angular/forms';
import {FormsModule,ReactiveFormsModule} from '#angular/forms';
#Component({
selector: 'app-addproduct',
templateUrl: './addproduct.component.html',
styleUrls: ['./addproduct.component.css']
})
export class AddproductComponent implements OnInit {
product: Product;
constructor(private helper: ProductsService) { }
ngOnInit(): void {
}
onFileChange(event){
var data = {
"file": event.target.file
}
this.helper.uploadProduct(data).subscribe(d => {
this.product.path = d;
});
}
uploadProduct(title: string, category: string, imported: string, type: string, description: string){
this.product.mapProduct(title, description, type, category, imported);
this.helper.saveProduct(this.product);
}
}
TIA! :)

Related

How to verify validion of form inside form?

I'm trying to verify a form that's inside a form.
The idea is to create a user's html page with the option to create a contact list.
My goal is to verify both forms with one click on the 'Save User Profile' button.
My question is How to verify the validion of the inner form inside the main form?
NO BOOTSTRAP AND OTHERS.
Main form:
HTML:
<div class="container"
style="width: 60%;">
<h5>User Profile</h5>
<div>
<form (ngSubmit)="onSubmit()"
#f=ngForm>
<!-- Name -->
<div class="column">
<label for="name"
style="margin-left: 5px;">Name</label><br>
<input type="text"
[(ngModel)]="user.name"
name="name"
id="name"
required
minlength="2"
maxlength="30"
#n="ngModel">
<p *ngIf="!n.valid && n.touched"
style="color: red;"> Please insert a name with 2-30 chars</p>
</div>
<!-- Organization -->
<div class="column">
<label for="orga"
style="margin-left: 5px;">Organization</label><br>
<input type="text"
[(ngModel)]="user.organization"
name="orga"
id="orga">
</div>
<br><br><br><br><br>
<h5>Contact Information</h5>
<div class="box">
<app-user-card *ngFor="let c of contacts; let i = index"
[id]="i"
[user]="user"></app-user-card>
<br><br>
</div>
<button type="button"
class="btn-add"
(click)="addContact()">Add Contact</button>
<button class="btn-save"
type="submit"
[disabled]="!f.valid">Save User Profile
</button>
</form>
</div>
TS:
export class UsersListComponent implements OnInit {
users: User[] = []
user: User = {
name: '',
organization: '',
contacts: []
}
id: number
contacts: Contact[] = []
contact: Contact = {
id: 0,
type: '',
label: '',
contact: ''
}
constructor() { }
ngOnInit(): void {
this.user.contacts = this.contacts
}
addContact() {
this.contacts.push(new Contact(this.id, this.contact.type, this.contact.label, this.contact.contact))
}
onSubmit() {
/* Upgrade option: Check if a user exists on the system and view his contacts*/
this.users.push(new User(this.user.name, this.user.organization, this.contacts))
console.log(this.users);
}
}
inner form:
HTML:
<div class="card">
<form #f = "ngForm">
<div class="column">
<label for="contactType">Type of Contact</label><br>
<select id="contactType"
[(ngModel)]=contact.type
name="cotactType"
style="width: 95%;"
required>
<option value="email">Email</option>
<option value="phone">Phone</option>
</select>
</div>
<div class="column">
<label for="label">Contact Label</label><br>
<input type="text"
[(ngModel)]="contact.label"
id="label"
name="lable"
style="width: 95%;"
required
minlength="2"
maxlength="20"
#l>
<p *ngIf="!l.valid && l.touched"
style="color: red;">Label is required!</p>
</div>
<div>
<label for="contact"
style="margin-left: 5px;">Email/Phon No.</label><br>
<input type="text"
[(ngModel)]=contact.contact
required
id="contact"
name="contact"
style="width: 98%;"
#c>
<p *ngIf="!c.valid && c.touched"
style="color: red;">Email/Phon No is required!</p>
</div>
<button type="button"
class="btn-remove"
style="left: 69%;position: relative;">Remove</button>
</form>
TS:
#Component({
selector: 'app-user-card',
templateUrl: './user-card.component.html',
styleUrls: ['./user-card.component.css']
})
export class UserCardComponent implements OnInit {
contact: Contact = {
id: 0,
type: '',
label: '',
contact: ''
}
#ViewChild("f") contactDetails: NgForm
#Input() id: number
constructor() { }
ngOnInit(): void {}
}

Display class content after clicking on a button reactjs

I am using reactjs, and I have two classes Table and APP each one is in an individual file(Table.js and App.js); in my App.js I wrote an html code where I have a button after clicking on that button I want to display Table content which is inside a render. I tried doing: <Button onClick={<Table/>}, but it doesn't work. Any suggestions?
import React, { Component } from 'react'
import './Table.css'
class Table extends Component {
constructor(props) {
super(props)
this.state = {
Offers: [
{ name: 'Name1', website: 25 },
{ name: 'Name2', website: 19},
{ name: 'Name3', website: 16},
{ name: 'Name4', website: 25}
],
}
}
renderTableHeader() {
let header = Object.keys(this.state.Offers[0])
return header.map((key, index) => {
return <th key={index}>{key.toUpperCase()}</th>
})
}
renderTableData() {
return this.state.Offers.map((offer, index) => {
const { name, website} = offer
return (
<tr >
<td>{name}</td>
<td>{website}</td>
</tr>
)
})
}
render() {
return (
<div>
<h1 id='title'>Start-ups List Table</h1>
<table id='offers'>
<tbody>
<tr>{this.renderTableHeader()}</tr>
{this.renderTableData()}
</tbody>
</table>
</div>
)
}
}
export default Table
import React, { Component} from 'react';
import {
Container, Col, Form,
FormGroup, Label, Input,
Button, Dropdown,
} from 'reactstrap';
import Axios from "axios";
import './App.css';
import Table from './Table';
class App extends Component {
render(){
return (
<div>
<div className="box">
<div className="element sourcedropdown" >
<label>Source :</label>
<select className="form-control" name="Sources" onChange={this.handleChange}>
<option selected>Select Source</option>
<option value="1">src1</option>
<option value="2">src2</option>
<option value="3">src3</option>
</select>
</div>
<div className="element Techdropdown">
<label>Technology :</label>
<select className="form-control" name="Tech" onChange= {this.handleChange}>
<option selected>Select Technology</option>
<option className="dropdown-item" value="1">tech1</option>
<option className="dropdown-item" value="2">tech2</option>
<option className="dropdown-item" value="3">tech3</option>
</select>
</div>
<div id="contrat" className="element contrat">
<label>Contract :</label>
<select className="form-control" name="Tech" onChange= {this.handleChange}>
<option selected>Select contract</option>
<option className="dropdown-item" value="1">V1</option>
<option className="dropdown-item" value="2">V2</option>
<option className="dropdown-item" value="3">V3</option>
<option className="dropdown-item" value="3">V4</option>
</select>
</div>
<div id="checkbox" className ="element checkbox">
<label check>
<input type="checkbox" onChange= {this.handleChange} />{' '}
Remote
</label>
</div>
<Button className="button" onClick={<Table/>}>Submit</Button> //here where i want to call Table
</div>
</div>
);
}
}
export default App;
You have placed Table rendering inside onClick method callback. The onClick is method is just a callback. You have to conditionally display Table based on a state as your are displaying other tags. You can changed the state based on Button click.
https://codesandbox.io/s/morning-hooks-ie74g?file=/src/App.js:0-2760
import React, { Component } from "react";
import {
Container,
Col,
Form,
FormGroup,
Label,
Input,
Button,
Dropdown
} from "reactstrap";
import Axios from "axios";
import Table from "./Table";
class App extends Component {
constructor (props) {
super(props);
this.state = {
displayTable: false
};
}
render () {
return (
<div>
<div className="box">
<div className="element sourcedropdown">
<label>Source :</label>
<select
className="form-control"
name="Sources"
onChange={this.handleChange}
>
<option selected>Select Source</option>
<option value="1">src1</option>
<option value="2">src2</option>
<option value="3">src3</option>
</select>
</div>
<div className="element Techdropdown">
<label>Technology :</label>
<select
className="form-control"
name="Tech"
onChange={this.handleChange}
>
<option selected>Select Technology</option>
<option className="dropdown-item" value="1">
tech1
</option>
<option className="dropdown-item" value="2">
tech2
</option>
<option className="dropdown-item" value="3">
tech3
</option>
</select>
</div>
<div id="contrat" className="element contrat">
<label>Contract :</label>
<select
className="form-control"
name="Tech"
onChange={this.handleChange}
>
<option selected>Select contract</option>
<option className="dropdown-item" value="1">
V1
</option>
<option className="dropdown-item" value="2">
V2
</option>
<option className="dropdown-item" value="3">
V3
</option>
<option className="dropdown-item" value="3">
V4
</option>
</select>
</div>
<div id="checkbox" className="element checkbox">
<label check>
<input type="checkbox" onChange={this.handleChange} /> Remote
</label>
</div>
<Button
className="button"
onClick={() => {
this.setState({ displayTable: true });
}}
>
Submit
</Button>
</div>
{this.state.displayTable ? <Table /> : ""}
</div>
);
}
}
export default App;

Form group dropdown menu content not present in json, Angular 6

I have made a form group where the purpose is to register cars.
On submit it is generating a JSON from the values inserted.
The issue is that the value from the dropdown menu is not present in the JSON.
The dropdown menu is populated with the choices shown below and is the first entry in the form group.
The label names and error messages are in Norwegian but the essence should be there.
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-12 offset-md-4">
<h3>Fyll inn</h3>
<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-group">
<label for="CarType">Bil type</label>
<select id="CarType" name="CarType" [(ngModel)]="CarType" class="form-control">
<option [ngValue]="CarType" *ngFor="let CarType of CarTypes" [value]="CarType.Id">{{CarType.Name}}</option>
</select>
</div>
<div class="form-group">
<label for="LicensePlate">Skiltnummer</label>
<input type="text" class="form-control" name="LicensePlate" [(ngModel)]="model.LicensePlate" #LicensePlate="ngModel" [ngClass]="{ 'is-invalid': f.submitted && LicensePlate.invalid }" required />
<div *ngIf="f.submitted && LicensePlate.invalid" class="invalid-feedback">
<div *ngIf="LicensePlate.errors.required">Skiltnummer er påkrevd</div>
</div>
</div>
<div class="form-group">
<label for="KilometersDriven">Kilometerstand</label>
<input type="number" class="form-control" name="KilometersDriven" [(ngModel)]="model.KilometersDriven" #KilometersDriven="ngModel" [ngClass]="{ 'is-invalid': f.submitted && KilometersDriven.invalid }" required />
<div *ngIf="f.submitted && KilometersDriven.invalid" class="invalid-feedback">
<div *ngIf="KilometersDriven.errors.required">Kilometerstand er påkrevd</div>
</div>
</div>
<div class="form-group">
<label for="Seats">Antall seter</label>
<input type="number" class="form-control" name="Seats" [(ngModel)]="model.Seats" #Seats="ngModel" [ngClass]="{ 'is-invalid': f.submitted && Seats.invalid }" required />
<div *ngIf="f.submitted && Seats.invalid" class="invalid-feedback">
<div *ngIf="Seats.errors.required">Antall seter er påkrevd</div>
</div>
</div>
<div class="form-group">
<label for="Gears">Antall gir</label>
<input type="number" class="form-control" name="Gears" [(ngModel)]="model.Gears" #Gears="ngModel" [ngClass]="{ 'is-invalid': f.submitted && Gears.invalid }" required />
<div *ngIf="f.submitted && Gears.invalid" class="invalid-feedback">
<div *ngIf="Gears.errors.required">Antall gir er påkrevd</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Registrer</button>
</div>
</form>
</div>
</div>
</div>
</div>
import { Component, OnInit } from '#angular/core';
import { CarType } from 'src/shared/models/cartype.model';
#Component({
selector: 'app-add-car',
templateUrl: './add-car.component.html',
styleUrls: ['./add-car.component.css']
})
export class AddCarComponent implements OnInit {
CarTypes: CarType[] = [
{ Id: 1, Name: 'SUV' },
{ Id: 2, Name: 'Coupe' },
{ Id: 3, Name: 'Sedan' }
]
model: any = {};
onSubmit() {
console.log(this.model)
alert('SUCCESS \n\n' + JSON.stringify(this.model))
}
constructor() { }
ngOnInit() {
}
}
export class CarType {
Id: number;
Name: String;
}
To the right is a link to the fill in form on the website.
To the right is a image of the JSON reply created from the previous picture
{LicensePlate: "RH123123", KilometersDriven: 120000, Seats: 5, Gears: 6}
You didn't bind it with the model object [(ngModel)]="CarType"
<select id="CarType" name="CarType" [(ngModel)]="model.carType" class="form-control">
<option [ngValue]="CarType" *ngFor="let CarType of CarTypes" [value]="CarType.Id">{{CarType.Name}}</option>
</select>

How to get the value of dynamically created input in angular

I have created an empty hash map of a 'question' object in angular according to the no. of questions given in the earlier page.Then i am rendering the 'question' objects in the hash map when the page initializes.I want to get the values of the inputs given for each question object when the user clicks 'add paper' button which calls the 'test()' function.What is the best way to do this?I was thinking of using viewChild to get the values,but it returns undefined.Thanks in advance.
Component File
import { Component, OnInit, ViewChild,ElementRef, ViewChildren } from '#angular/core';
import { SharedserviceService } from "../services/sharedservice.service";
#Component({
selector: 'app-admin-paper',
templateUrl: './admin-paper.component.html',
styleUrls: ['./admin-paper.component.css']
})
export class AdminPaperComponent implements OnInit {
public paperID:any;
public noOfQuestions : number ;
public message : any;
public i : number ;
public questionSet = {};
public question0 : any;
#ViewChildren('testchild') testchild :ElementRef;
constructor(private shared : SharedserviceService) { }
ngOnInit() {
this.shared.currentMessage.subscribe((message)=>{
this.message = message;
});
this.paperID = this.message.paperID;
this.noOfQuestions = this.message.noOfQuestions;
for (this.i =0;this.i < this.noOfQuestions;this.i++){
const question = {
'paperID': this.paperID,
'questionID': this.i,
'question': '',
'answers': [],
'correctAnswer':''
};
this.questionSet[this.i] = question;
}
console.log(this.questionSet);
}
test(){
//console.log(this.testchild.nativeElement.value);
for (this.i =0;this.i < this.noOfQuestions;this.i++){
const question = {
'paperID': this.paperID,
'questionID': this.i,
'question': `question${this.i}');`,
'answers': [`question${this.i}answer0`,`question${this.i}answer1`,`question${this.i}answer2`,`question${this.i}answer3`],
'correctAnswer':'vghvhg'
};
console.log(question);
this.questionSet[this.i] = question;
}
console.log("clicked");
console.log(this.questionSet);
}
}
HTML File
<ng-container *ngIf="questionSet" >
<div class="panel panel-widget border-right" *ngFor="let question of questionSet | keyvalue; let i= index;" style="text-align: left; background-color: white; padding: 10px; border-radius: 10px;border-style: solid; border-width: 3px; border-color: #1aa3ff;">
<div class="container">
<div class="row">
<div class="form-group col-md-10">
<label> Question {{question.value.questionID+1}}</label>
<input type="text" class="form-control" #question{{i}} aria-describedby="emailHelp" placeholder="Enter question Here">
</div>
</div>
<div class= "row">
<div class="col-sm-2">
<div class="form-group">
<label>Answer 1</label>
<input type="email" class="form-control" id="question{{i}}answer0" aria-describedby="emailHelp" placeholder="Answer 1">
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Answer 2</label>
<input type="email" class="form-control" id="question{{i}}answer1" aria-describedby="emailHelp" placeholder="Answer 2">
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Answer 3</label>
<input type="email" class="form-control" id="question{{i}}answer2" aria-describedby="emailHelp" placeholder="Answer 3">
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Answer 4</label>
<input type="email" class="form-control" id="question{{i}}answer3" aria-describedby="emailHelp" placeholder="Answer 4">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Correct Answer</label>
<input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Correct Answer">
</div>
</div>
<div class="col-sm-6">
<button type="submit" style="margin-top:6%" (click)="addQuestion($event,question,'new')" class="btn btn-primary mb-2">Add Question</button>
</div>
</div>
<br><br>
</div>
</ng-container>
<button type="button" class="btn btn-primary btn-lg btn-block" (click)="test()">Add Paper</button>
*ngIf="questionSet" always be true because an empty object is a truthy value in js. Convert your ngOnInit like this
ngOnInit() {
this.shared.currentMessage.subscribe((message)=>{
this.message = message;
this.paperID = this.message.paperID;
this.noOfQuestions = this.message.noOfQuestions;
for (let i =0; i < this.noOfQuestions; i++){
const question = {
'paperID': this.paperID,
'questionID': this.i,
'question': '',
'answers': [],
'correctAnswer':''
};
this.questionSet[this.i] = question;
}
console.log(this.questionSet);
});
}

Angular 4 Forms --> Search Results from Input

So I am having a bit of a problem. I have to create a search page for a travel agency. In this example, I'm booking a flight. I have no idea how to display each result based off the inputs of the form ahhhhh. I've been trying but I ran outta mental energy for the day smh.
Here is some code:
HTML
<!-- Search Form -->
<form class="" action="index.html" method="post">
<h1> Let's Go. </h1>
<hr>
<select class="" name="">
<option value="">Select means of Travel</option>
<option value="">Flight</option>
</select>
<label for="Travel Start Date">Travel Start Date</label>
<input type="date" name="" value="Travel Start Date">
<label for="Travel End Date">Travel End Date</label>
<input type="date" name="" value="Travel End Date">
<select class="" name="">
<option value="">Departure Location</option>
<option value="Atlanta">Atlanta</option>
</select>
<select class="" name="">
<option value="">Arrival Location</option>
<option value="San Francisco">San Francisco</option>
</select>
<select class="" name="">
<option value="">Product Class</option>
<option value="">Economy</option>
</select>
<input style="width: 100px; background-color: green; color: #eef; height: 40px; border-radius: 50px; margin: 0 auto; margin-top: 50px;"
type="submit" name="" value="Submit" onclick="">
</form>
<!-- Results -->
<div class="result">
<ul>
<li *ngFor = 'let group of displayItems'>
<div class="flight-card">
<div class="availability">
<h5> Availability: {{group.availability}} </h5>
</div>
<div class="price">
{{ group.price.symbol }}
{{ group.price.amount }}
<p>{{ group.price.currency }}</p>
</div>
<div class="arrival">
<h5> Arrival City: </h5>{{group.arrival.city}} <br>
<h5> Arrival Airport Name: </h5>{{group.arrival.airport.name}} <br>
<h5> Arrival Time: </h5>{{group.arrival.city}} <br><br>
</div>
<hr>
<div class="depature">
<h5> Depature City: </h5>{{group.departure.city}} <br>
<h5> Departure Airport Name: </h5>{{group.departure.airport.name}} <br>
<h5> Departure Time: </h5>{{group.departure.time}} <br><br>
</div>
</div>
</li>
</ul>
</div>
(In root App)
Component.Ts
import { Component } from '#angular/core';
import { Http, Response, RequestMethod, RequestOptions, Headers } from '#angular/http';
import { NgIf } from '#angular/common';
import { Form } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
result;
errorFromSubscribe;
errorFromCatch;
displayItems;
// Inject HttpClient into your component or service.
constructor(private http: Http) {}
ngOnInit(): void {
// Making the HTTP Request
this.http
// Get API data
.get('https://api.myjson.com/bins/1gb9tf')
// Subscribe
.subscribe( (res: Response) => {
// Parses the response to JSON.
this.result = res.json();
this.displayItems = this.result['results'];
console.log(this.result);
}, error => {
console.log(error)
this.errorFromSubscribe = error;
});
}
title = 'app';
}
You need to use pipe for filtering by applying a specific logic to filter items for search
<li *ngFor="let group of displayItems | filter: term">
and the pipe as follows,
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any, term: any): any {
if (term === undefined) return items;
return items.filter(function(item) {
for(let property in item){
if (item[property] === null){
continue;
}
if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
return true;
}
}
return false;
});
}
}
DEMO