Angular 4 Forms --> Search Results from Input - html

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

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 {}
}

Component not rendering on Angular, It shows no error

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! :)

my 'ngSubmit' sometimes error

so I have this html code.. i tried using (click) function, and its still like this
<div class="container">
<h1><a [routerLink]="['/databuku']"><img src="images/images.png" width="42" height="42"></a>
Add New Book</h1>
<div class="row">
<div class="col-md-6">
<form (ngSubmit)="saveBuku()" #bukuForm="ngForm">
<div class="form-group">
Judul
<input type="text" class="form-control" [(ngModel)]="buku.judul" name="judul" required>
</div>
<div class="form-group">
Author
<input type="text" class="form-control" [(ngModel)]="buku.author" name="author" required>
</div>
<div class="form-group">
Description
<textarea class="form-control" [(ngModel)]="buku.description" name="description" required cols="40" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" [disabled]="!bukuForm.form.valid">Save</button>
</div>
</form>
</div>
</div>
</div>
here is my ts file
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-tambah-buku',
templateUrl: './tambah-buku.component.html',
styleUrls: ['./tambah-buku.component.css']
})
export class ComponentTambahBuku implements OnInit {
buku = {};
constructor(private http: HttpClient, private router: Router) { }
ngOnInit() {
}
saveBuku() {
this.http.post('http://localhost:8080/buku', this.buku)
.subscribe(res => {
let id = res['id'];
this.router.navigate(['/detail-buku/', id]);
}, (err) => {
console.log(err);
}
);
}
}
no errors found when I open localhost:4200, its just when i press the save button, its like the button doesn't working, not saving and not going to 'detail-buku' page

How to pass the multiple values from view to method without two way binding?

I have the dropdown(Route type in Code) while changing the dropdown value, I need to pass the gender value and route type id of the dropdown to my get data method.
Now in my HTML I wrote the only change event, I tried with two-way binding but I am getting the error, what I need, while changing dropdown I need to pass gender value and dropdown id.
HTML File:
<br>
<br>
<div class="text-center">
<div class="container">
<div class="jumbotron">
<form>
<h3>Manage Content</h3>
<br>
<h4>Select Gender:</h4>
<label class="radio-inline"><input type="radio" #gender name="gender" value="1" checked>Male</label>
<label class="radio-inline"><input type="radio" #gender name="gender" value="2">Female</label>
<br>
<br>
<h4>Select Routing Type:</h4>
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-6">
<select class="form-control" (change)="getdata()">
<option>Choose Route Type</option>
<option *ngFor="let manage of dropdown" value="{{manage.Id}}">{{manage.Name}}</option>
</select>
</div>
</div>
<br>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">Category</th>
<th scope="col">Created By</th>
<th scope="col">Date Created</th>
<th scope="col">File Name</th>
<th scope="col">File</th>
</tr>
</thead>
<tbody>
<ng-template [ngTemplateOutlet]="tmplt"></ng-template>
</tbody>
</table>
<input class="btn btn-primary" (click)="Save()" type="button" value="Save" />
<input class="btn btn-danger" type="button" value="Cancel" />
</form>
</div>
</div>
</div>
<ng-template #tmplt>
<tr *ngFor="let manage of managecontent; let i =index">
<td *ngIf="manage.CategoryTypeId == 1">{{manage.Categorytype[0]}}</td>
<td *ngIf="manage.CategoryTypeId == 2">{{manage.Categorytype[1]}}</td>
<td>{{manage.CreatedBy}}</td>
<td>{{manage.CreatedDate}}</td>
<td>{{manage.DocumentDetails.DocName}}</td>
<td>
<app-file-upload [documentModel]="manage.DocumentDetails" [isMultipleFile]="true" [model]="manage" (emitterFile)="fileSelect($event)"></app-file-upload>
</td>
<td>
<input class="btn btn-danger" type="button" value="Remove" (click)="Delete(manage.DocumentDetails.Id)" />
</td>
</tr>
</ng-template>
TS File:
import { Component, OnInit, TemplateRef, ViewChild } from "#angular/core";
import { ManageContentService } from "../Service/managecontent.service";
import { ManageContentModel, dropdownmodel } from "../Model/managecontent.model";
import { DocumentDetails } from "../Model/document.model";
import { CommonModule } from '#angular/common';
import { Observable } from 'rxjs/Rx';
#Component({
selector: 'manage-content',
templateUrl: './app/QadAdminConfig/Templates/managecontent.component.html',
providers: [ManageContentService]
})
export class ManageContentComponent implements OnInit {
data: any;
result: any;
dropdown: Array<dropdownmodel> = [];
managecontent: Array<ManageContentModel> = [];
content: ManageContentModel;
#ViewChild("tmplt") tmpltTbl: TemplateRef<any>;
ngOnInit() {
this.getRouType();
this.getdata(1, 1);
}
constructor(private _managecontentService: ManageContentService) {
}
fileSelect(model: ManageContentModel) {
this.managecontent.forEach(x => {
if (JSON.stringify(x) == JSON.stringify(model))
x = model;
});
console.log(this.managecontent);
}
getRouType() {
this._managecontentService.GetRouteType().subscribe(
data => {
if (data.Success) {
this.dropdown = data.Result as dropdownmodel[];
}
});
}
getdata(gender: number, routetypeid: number) {
this._managecontentService.Get(gender, routetypeid).subscribe(
data => {
if (data.Success) {
this.managecontent = data.Result;
console.log(this.managecontent);
}
});
}
Delete(Id: number) {
this._managecontentService.Delete(Id).subscribe(data => {
});
}
Save() {
console.log('model:', this.managecontent);
this._managecontentService.Save(this.managecontent).subscribe(x => {
this.result = x;
console.log(this.result);
});
}
}
You can do this by changing your inputs to the following:
<label class="radio-inline"><input type="radio" #male name="gender" value="1" checked>Male</label> // changed selector from #gender to #male
<label class="radio-inline"><input type="radio" #female value="2" name="gender">Female</label> // changed selector from #gender to #female
and modifying your (change) binding to this:
<select class="form-control" (change)="getdata(male.checked ? 1: 2, $event.target.value)">

Angular data ist not defined

simple question, I try to implement a login form and store it into the variable "data". But the console tells me ERROR ReferenceError: data is not defined.
But I did defined it. What did I do wrong?
Loginform.component.ts:
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-loginform',
templateUrl: './loginform.component.html',
styleUrls: ['./loginform.component.css']
})
export class LoginformComponent implements OnInit {
data = {};
constructor(private router:Router, private user:UserService) { }
ngOnInit() {
}
formSubmit() {
if(data.username == 'admin' && data.passwd == 'test'){
user.setUserLoggedIn();
this.router.navigate(['dashboard']);
}
};
}
loginform.component.html:
<div class="loginFlexCenter">
<div class="loginForm">
<h2> Studienverlaufsplan Login </h2>
<hr>
<form class="inputDiv" (ngSubmit)="formSubmit()">
<div class="inputDiv">
<label>Username:</label>
<input class="txtInput" type="text" name="username" [(ngModel)]="data.username"><br/>
</div>
<div class="inputDiv">
<label>Password:</label>
<input class="txtInput" type="password" name="password" [(ngModel)]="data.passwd">
</div>
<div class="inputDivHalf">
<input class="txtInput" type="submit" value="Submit"/>
<input routerLink="/register" routerLinkActive="active" class="txtInput" type="submit" value="Register"/>
</div>
</form>
</div>
</div>