How to map and bind Dropdown items in Angular 6? - javascript

i have a dropdown which has option like testOptions.
i get data from service for these option to Map like 'Y' for Yes , 'N' for 'No' and 'U' for unconfirmed in property optionTest .
import { Component, OnInit, createPlatformFactory } from '#angular/core';
#Component({
selector: 'app-test-information',
templateUrl: './app-test-information.component.html',
styleUrls: ['./app-test-information.component.scss']
})
export class TestInfoComponent implements OnInit {
Id :Items;
public testOptions: Items[] = [
{
id: 1,
name: 'NA',
},
{
id: 2,
name: 'Yes',
},
{
id: 3,
name: 'No',
},
{
id: 4,
name: 'Unconfirmed'
}
];
ngOnInit() {
this.infoService.getData()
.subscribe((result :InfoResults ) => this.data = result
, undefined,
() => {
if (this.data) {
this.readOnlyData()
}
})
readOnlyData() {
//here i am trying to find item in testOptions and bind the data from service
this.Id=this.testOptions.find((item) => item.name === "Yes" ) ;
}
}
<!-- Model class for items : -->
export class Items {
public id ?: number;
public name : string;
}
export class InfoResults {
public optionTest : string;
}
how we can map or get this.id if options from service are coming in data like 'Y' for Yes , 'N' for 'No' and 'U' for unconfirmed?
Please help.
Thanks!

Related

Filter array by array with true or false value Angular

A have a client class I have a column with a sting column isSimple 'TAK' or 'NIE' (YES or NO in English) in my Class. In this class a have an argument a Canal and this class I have an argument 'Procudent' or 'Handel'. In my Reactive Form a have a form where a may a filter a Producent, Handel and Simple and I send this information to my HomeController. Now I want to filter this clients where I clicked true in my input near Handel, Producent or Simple by this columns.
My code is :
I recive this data in my HomeController array :
[
{ name: "Producent", checked: true },
{ name: "Handel", checked: true },
{ name: "Simple", checked: true }
];
My class client :
export class Client {
clientId: number;
name: string ;
district: string;
province: string;
zip: string;
city: string;
full_Address: string;
latitude: number;
longitude: number;
segment: string;
ph: string;
bh: number;
canal: string;
isSimple: string;
}
I send through this class :
import { Component, EventEmitter, OnInit, Output } from '#angular/core';
import { FormArray, FormBuilder, FormGroup } from '#angular/forms';
import { IBox } from 'src/app/Models/IBox';
#Component({
selector: 'app-type-of-client',
templateUrl: './type-of-client.component.html',
styleUrls: ['./type-of-client.component.css']
})
export class TypeOfClientComponent implements OnInit {
box_data: IBox[] = [
{ name: "Producent", checked: true },
{ name: "Handel", checked: true },
{ name: "Simple", checked: true }
];
#Output() typeOfClient = new EventEmitter<{}>();
form_model: FormGroup = this.fb.group({
search_text: this.fb.control(""),
boxes: this.fb.array(
this.box_data.map((box: IBox) => {
return this.fb.group({ checked: [box.checked],name:[box.name] });
})
)
})
constructor(private fb: FormBuilder) { }
get boxes() {
return this.form_model.get("boxes") as FormArray;
}
ngOnInit(): void {
this.boxes.valueChanges.subscribe(
(response) =>{
let clients : IBox[] =[];
for (let index = 0; index < response.length; index++) {
const element = response[index];
clients.push(element);
}
// let clients : IBox[] = this.box_data;
this.typeOfClient.emit(clients);
}
);
}
}
And now a want to try use method method include but it doesn't work. I filter like this my client throung another argument.
filterClients() {
console.log(this.checkedPH);
console.log(this.checkedSegment);
const typeClient = this.checkedTypeOfClient
this.currentClientList = this.baseClientList;
this.currentClientList = this.currentClientList.filter(client => {
return this.checkedSegment.includes(client.segment) && this.checkedPH.includes(client.ph);
});
}
In general you has a parent component that received the value
<!--see that you received the output using "$event"-->
<app-type-of-client (typeOfClient)="filter($event)"></app-type-of-client>
if your parent component I mush suppose you has an array with all the clients, use an auxiliar variable filterClients
allClients:Clients[];
filterClients:Clients[]=[]
The problem is that you received an strange object. I'm going to transform this response before make the filter
So, create a function
filter(response:any[]){
const filter={
Producent:response.find(x=>x.name="Producent").checked
Handel:response.find(x=>x.name="Handel").checked
Simple:response.find(x=>x.name="Simple").checked
}
this.filterClients=this.allClients.filter(x=>(x.canal=="Producent" && filter.Producent) &&
(x.canal=="Handel" && filter.Handel) &&
((x.Simple=="TAK" && filter.Simple) || (x.Simple=="NIE" && !filter.Simple)))
}
And iterate over filterClients.
NOTE: if you always received the three values and the values are in order. Some like
this.boxes.valueChanges.subscribe(res=>{
this.typeOfClient.emit(res.map(x=>x.checked)) //<--this emit, e.g. [true,false,true]
})
You can filter like
filter(response:any[]){
this.filterClients=this.allClients.filter(x=>(x.canal=="Producent" && response[0]) &&
(x.canal=="Handel" && response[1]) &&
((x.Simple=="TAK" && response[2]) || (x.Simple=="NIE" && !response[2])))
}

Empty response when trying to fetch mock data from Service

I want to fetch and display data from Array of Objects.
I have created the parameterized routes.
1. app-routing.module.ts
const routes: Routes = [
{
path: 'all-trades',
component: AllTradesComponent,
},
{
path: 'crop/:name', component: CropComponent
}]
2. Crop.ts
export class Crop {
name: string;
checked: boolean;
subCategory: Subcategory[];
}
export class Subcategory {
id: number;
name: string;
isActive: boolean;
}
3. CropData.ts
Here is my Array of object, I want to access subCategory and display the name on webpage.
for example: When user click on Rice then its should get the result like 'Basmati', 'Ammamore'
OR
When user click on Wheat then its should get the result like 'Durum', 'Emmer'
OR
When user click on Barley then its should get the result like 'Hulless Barley', 'Barley Flakes'
import { Crop } from './Crop';
export const CROP: Crop[] = [
{
name: 'Rice',
checked: true,
subCategory: [
{
id: 1,
name: 'Basmati',
isActive: true,
},
{
id: 2,
name: 'Ammamore',
isActive: true,
},
],
},
{
name: 'Wheat',
checked: true,
subCategory: [
{
id: 1,
name: 'Durum',
isActive: true,
},
{
id: 2,
name: 'Emmer',
isActive: true,
},
],
}, {
name: 'Barley',
checked: true,
subCategory: [
{
id: 1,
name: 'Hulless Barley',
isActive: true,
},
{
id: 2,
name: 'Barley Flakes',
isActive: true,
},
],
}
]
4.1 crop.service.ts
// First I tried this logic
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs';
import { skipWhile } from 'rxjs/operators';
import { Crop } from '../shared/Crop';
import { CROP } from '../shared/cropdata';
#Injectable({
providedIn: 'root'
})
export class CropService {
constructor() { }
CropData: Crop
getCrop(name: string): Crop {
return this.CropData.filter((crop) => (crop.name === name))[0];
}
}
4.2 crop.service.ts
// Then I tried this logic
export class CropService {
private selectedCrop= new BehaviorSubject<Crop>(null);
setCrop(crop:Crop){
this.selectedCrop.next(crop);
}
getCrop(){
this.selectedCrop.asObservable().pipe(skipWhile(val=> val === null));
}
}
I failed in both the cases.
5.1 all-trades.components.ts
// First tried using function
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { Crop } from 'src/app/shared/Crop';
import { CropService } from '../crop.service';
#Component({
selector: 'app-all-trades',
templateUrl: './all-trades.component.html',
styleUrls: ['./all-trades.component.css'],
})
export class AllTradesComponent implements OnInit {
constructor(private service: CropService, private router: Router) { }
// Here I tried to make use of function but still its doesnot giving me the desire result
onSelect(selectedCrop:Crop){
this.service.setCrop(selectedCrop);
this.router.navigateByUrl(`crop/${crop.name}`);
}
onChange(event, index, item) {
item.checked = !item.checked;
console.log(index, event, item);
}
ngOnInit(): void { }
}
5.1 all-trades-component.html
<app-header></app-header>
<div
fxLayout="row"
fxLayout.lt-md="column"
fxLayoutAlign="space-between start"
fxLayoutAlign.lt-md="start stretch"
>
<div class="container-outer" fxFlex="20">
<div class="filters">
<section class="example-section">
<span class="example-list-section">
<h1>Select Crop</h1>
</span>
<span class="example-list-section">
<ul>
<li *ngFor="let crop of crops">
<mat-checkbox
[checked]="crop.checked"
(change)="onChange($event, i, crop)"
>
{{ crop.name }}
</mat-checkbox>
</li>
</ul>
</span>
</section>
<div class="content container-outer" fxFlex="80">
<mat-card
class="crop-card"
style="min-width: 17%"
*ngFor="let crop of crops"
[hidden]="!crop.checked"
>
<!-- here i call the function -->
<a (click)="onSelect(crop)" routerLinkActive="router-link-active">
<mat-card-header>
<img
mat-card-avatar
class="example-header-image"
src="/assets/icons/crops/{{ crop.name }}.PNG"
alt="crop-image"
/>
<mat-card-title>{{ crop.name }}</mat-card-title>
<mat-card-subtitle>100 Kgs</mat-card-subtitle>
</mat-card-header>
</a>
<mat-card-content>
<p>PRICE</p>
</mat-card-content>
</mat-card>
</div>
</div>
<app-footer></app-footer>
crop-componet.ts
import { Component, OnInit } from '#angular/core';
import { Subscription } from 'rxjs';
import { Crop } from 'src/app/shared/Crop';
#Component({
selector: 'app-crop',
templateUrl: './crop.component.html',
styleUrls: ['./crop.component.css']
})
export class CropComponent implements OnInit {
service: any;
crop: any;
route: any;
cropservice: any;
sub: Subscription;
constructor() { }
ngOnInit(): void {
// let name = this.route.snapshot.params['name'];
// this.crop = this.cropservice.getCrop(name);
this.sub = this.route.paramMap.subscribe(params => {
let name = params.get("name")
this.crop = this.cropservice.getCrop(name)
})
}
}
7. crop-component.html
<div *ngFor="let category of crop.subCategory">{{category.id}}</div>
This is my eniter code I dont know where I am going wrong please help in fetching data from arrays of object.
[![enter image description here][1]][1]
This is my all-trades.component.html output
When I click Rice I get this as output (Url get change )
[![enter image description here][2]][2]
When I click Wheat I get this
[![enter image description here][3]][3]
And so on....
I just want to display the name of subCategory Array.
Please give me the solution.
[1]: https://i.stack.imgur.com/kxdyj.png
[2]: https://i.stack.imgur.com/OOAtc.png
[3]: https://i.stack.imgur.com/PVcfT.png
On your 4.1 you seem to forget to assign your mock data into your variable
....
import { CROP } from '../shared/cropdata';
#Injectable({
providedIn: 'root'
})
export class CropService {
constructor() { }
CropData: Crop[] = CROP; // Assign the value
getCrop(name: string): Crop {
return this.CropData.filter((crop) => (crop.name === name))[0];
}
}
On your 4.2, you forgot to assign your mock data as well in your BehaviorSubject if you end up using this method. BehaviorSubjects are known to emit initial data
...
import { CROP } from '../shared/cropdata';
export class CropService {
private selectedCrop = new BehaviorSubject<Crop[]>(CROP); // Pass CROP mock data
setCrop(crop: Crop[]) {
this.selectedCrop.next(crop);
}
getCrop() {
this.selectedCrop.asObservable().pipe(skipWhile(val=> val === null));
}
}
Have created a Stackblitz Demo for your reference. You can check the console for the response

Angular how to display the result of a post request in a component

In my Angular application I am trying to display the result of a post request in another component (i.e. confirmation page). I wanted to know what would be the best way for this. In my component the code does a post request which posts to the server as follows:
import { Component, OnInit } from '#angular/core';
import { ReactiveFormsModule } from '#angular/forms';
import { FormGroup, FormControl } from '#angular/forms';
import { Validators } from '#angular/forms';
import { FormBuilder } from '#angular/forms';
import { Request } from '../../models/request.model'
import { Router } from '#angular/router';
import { Observable } from 'rxjs';
import { AppComponent } from '../../../app.component';
import { nowService } from '../../services/now.service';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '#angular/common/http';
#Component({
selector: 'app-service-request',
templateUrl: './service-request.component.html',
styleUrls: ['./service-request.component.scss']
})
export class ServiceRequestComponent implements OnInit {
public loading = false;
private customer_id = this.appComponent.customer_id;
serviceForm;
u_destination_country = [
{ value: 'Choose an option' },
{ value: 'United Kingdom', },
{ value: 'United States of America', },
{ value: 'Russia', },
{ value: 'Moscow', },
{ value: 'Africa', },
];
users = [
{ id: 'Select an option', },
{ id: '1', },
{ id: '2', },
{ id: '3', },
];
devices = [
{ id: 'Select an option', },
{ id: '1', },
{ id: '2', },
{ id: '3', },
];
constructor(private service: nowService,
private appComponent: AppComponent,
private router: Router,
private http: HttpClient
) {
}
ngOnInit() {
this.serviceForm = new FormGroup({
customer_id: new FormControl(this.customer_id),
si_id: new FormControl('', Validators.required),
u_destination_country: new FormControl(this.u_destination_country[0], Validators.required),
u_short_description: new FormControl('', Validators.compose([
Validators.required,
Validators.minLength(5),
Validators.maxLength(80)
])),
u_message_description: new FormControl(''),
});
}
onSubmit() {
this.http.post("/api/inc",
this.serviceForm.value,
{
headers: new HttpHeaders().set("Content-Type", "application/json")
}
).subscribe((response: any) => {
console.log(response);//On success response
this.router.navigate(['/inc/confirmation']);
}, (errorResponse: any) => {
console.log(errorResponse); //On unsuccessful response
});
if(this.serviceForm.invalid) {
this.serviceForm.setErrors({ ...this.serviceForm.errors, 'required': true });
return;
}
}
}
So what I want to do is display the value of the display_value which is something like:
result: Array(1)
0:
display_name: "number"
display_value: "INC001"
status: "inserted"
table: "incident"
For Angular 7.2.0 and higher:
You can make it by using NavigationExtras built into Angular Router. For this you have to add only two things.
First step:
Update this.route.navigate(['/inc/confirmation']) to this
this.router.navigate(['/inc/confirmation'],{state: {response}});
Second step:
In your second component you can access state by adding this to your code
const state = this.router.getCurrentNavigation().extras.state;
this.response = state.response;
Then you can display it.
For Angular 7 and lower:
First step:
Update this.route.navigate(['/inc/confirmation']) to this
this.router.navigate(['/inc/confirmation'],{queryParams: {value: response.result[0].display_value}});
Second step:
In your second component you can access state by adding this to your code
constructor(private route: ActivatedRoute){}
...
this.value = this.route.snapshot.queryParamMap.get('value');
Then you can display it.
When you don't want to use URL param:
You can create a service with one property
#Injectable({
providedIn: 'root'
})
export class SharedDataService {
public sharedData;
constructor() {
}
}
Then you can set sharedData before you redirect to another route.
constructor(private sharedService: SharedDataService){}
...
this.sharedService.sharedData = response;
this.route.navigate(['/inc/confirmation']);
You can get that data in your second component.
constructor(private sharedService: SharedDataService){}
...
this.response = this.sharedService.sharedData;

getData from multiple filters does not return anything

I can't get my getData function on app.component.ts to return the query with all the arguments for the API Request. I don't get any errors and I also can't console.log inside the function because it doesn't work. It skips everything I write inside getData. Any ideas?
app.component.ts
#Component({
/**
* Tag to show component in html
*/
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [MedicineService]
})
export class AppComponent implements OnInit, AfterViewInit {
#ViewChildren(FiltersComponent) filters: QueryList<FiltersComponent>;
title = 'Base Remédios';
_medicines: Medicine[];
resourceType: Filter[] = [
{
id: 'all',
title: 'All',
active: true,
},
{
id: 'texto1',
title: 'Texto1',
},
{
id: 'texto2',
title: 'Texto2',
},
{
id: 'texto3',
title: 'Texto3',
},
];
levels: Filter[] = [
{
id: 'grupo1',
title: 'Grupo1',
active: true,
},
{
id: 'grupo2',
title: 'Grupo2',
},
{
id: 'grupo3',
title: 'Grupo3',
},
];
private resources: Observable<any>;
constructor(private _medicineService: MedicineService) {
}
/**
* Function to get array itens of endpoints
*/
getMedicines(): void {
this._medicineService.getMedicines()
.subscribe(
resultArray => this._medicines = resultArray,
error => console.log(error));
}
ngOnInit(): void {
this.getMedicines();
}
ngAfterViewInit() {
const filters = this.filters.map(f => f.changeFilter);
console.log('oi');
this.resources = combineLatest(...filters).pipe(
map((filters: ActiveFilter[]) =>
filters.map(filter => `${filter.group}=${filter.id}`).join('&')),
switchMap(this.getData));
}
getData(query) {
return timer(1).mapTo('https://api.com?' + query);
}
}
filter.component.ts
export interface ActiveFilter {
id: number | string;
group: string;
}
export interface Filter {
id: string | string;
title: string;
active?: boolean;
}
#Component({
selector: 'app-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css']
})
export class FiltersComponent implements OnInit, OnDestroy {
#Input() group: string;
#Input() filters: Filter[] = [];
changeFilter;
ngOnInit(): void {
const initialFilter = this.filters.find(f => f.active);
this.changeFilter = new BehaviorSubject<ActiveFilter>({
group: this.group,
id: initialFilter.id
});
}
ngOnDestroy() {
this.changeFilter.unsubscribe();
}
select(filter: Filter) {
console.log('click funciona');
this.filters.forEach(filter => filter.active = false);
filter.active = true;
this.changeFilter.next({
group: this.group,
id: filter.id
});
}
}
filters.component.html
<ul>
<li *ngFor="let filter of filters" (click)="select(filter)" [ngClass]="{ active: filter.active }">
{{filter.title}}
</li>
</ul>
app.component.html
<section>
<app-filters [filters]="resourceType" group="type"></app-filters>
<app-filters [filters]="levels" group="level"></app-filters>
</section>
There is issue with the parameter you are passing to switchMap function of rxjs.
Modified code -
ngAfterViewInit() {
const filters = this.filters.map(f => f.changeFilter);
console.log('oi');
this.resources = combineLatest(...filters).pipe(
map((filters: ActiveFilter[]) =>
filters.map(filter => `${filter.group}=${filter.id}`).join('&')),
switchMap(()=>this.getData())); // <------ change here
}
Refer this - https://www.learnrxjs.io/operators/transformation/switchmap.html

Property 'subscribe' does not exist on type {}

Service.ts
import { Injectable } from '#angular/core';
const RELEASES = [
{
id: 1,
title: "Release 1",
titleUrl: "release-1",
year: "2016"
},
{
id: 2,
title: "Release 2",
titleUrl: "release-2",
year: "2016"
},
{
id: 3,
title: "Release 3",
titleUrl: "release-3",
year: "2017"
}
]
#Injectable()
export class ReleaseService {
visibleReleases =[];
getReleases(){
return this.visibleReleases = RELEASES.slice(0);
}
getRelease(id:number){
return RELEASES.slice(0).find(release => release.id === id)
}
}
Component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ReleaseService } from '../service/release.service';
import { ActivatedRoute, Params } from '#angular/router';
import { IRelease } from '../releases/release';
#Component({
selector: 'app-details',
templateUrl: './details.component.html',
styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {
private sub: any;
private release: string[];
constructor(
private _releaseService: ReleaseService,
private route: ActivatedRoute
) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = params['id'];
this._releaseService.getRelease(id).subscribe(release => this.release = release);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
IRelease interface
export class IRelease {
id: number;
title: string;
titleUrl: string;
year: string;
}
I'm trying to create a "Detail page" in my Angular4 app. What I want is to return a chosen item by the code below:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = params['id'];
this._releaseService.getRelease(id).subscribe(release => this.release = release);
});
}
And there's an error:
Property 'subscribe' does not exist on type '{ id: number; title: string; titleUrl: string; year: string; }'.
What have I done wrong?
Your ReleaseService#getRelease() method returns plain object, you do not need to subscribe to it. Subscribe is only for observables (more about them e.g. here).
You can simply do:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = params['id'];
this.release = this._releaseService.getRelease(id);
});
}

Categories