How to get the values of multiple checkboxes in Angular 8 - html

I am trying to get the values of the checkboxes that are selected. I have the following code:
<div style="background-color:lightblue;" >
<div class="content">
<label class="label">Province</label>
<div class="form-check form-check-inline" *ngFor = "let province of utilities.Provinces; let i of index">
<label class="form-check-label" for="inlineCheckbox1" >{{province}}</label>
<input class="form-check-input" [formControl]= "province" (change)="getSelectedProvinces()" type="checkbox" id="inlineCheckbox{{i}}" value="option1">
</div>
</div>
In .ts I have the following
import { Component, OnInit } from '#angular/core';
import { UtilitiesService } from '../_services/utilities.service';
import { Utilities } from '../models/utilities';
import { forEach } from '#angular/router/src/utils/collection';
#Component({
selector: 'app-filtering',
templateUrl: './filtering.component.html',
styleUrls: ['./filtering.component.css']
})
export class FilteringComponent implements OnInit {
utilities: Utilities;
provinces: string[] = [];
selectedProvinces: string[] = [];
selectedCategories: string[] = [];
constructor(private utilityService: UtilitiesService) { }
ngOnInit() {
this.loadUtilities();
}
loadUtilities() {
this.utilityService.getJSON().subscribe((utilities: Utilities) => {
this.utilities = utilities;
});
for (const province of this.utilities.Provinces) {
this.provinces.push(province);
}
}
getSelectedProvinces() {
this.selectedProvinces = [];
this.utilities.Provinces.forEach((_province, i) => {
if (_province.value) {
this.selectedProvinces.push(this.provinces[i]);
}
});
console.log(this.selectedProvinces);
}
}
In my utilities.ts I have the following:
export interface Utilities {
Provinces: Array<string>;
}
My service is written as follows:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Utilities } from '../models/utilities';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class UtilitiesService {
constructor(private http: HttpClient) {}
public getJSON(): Observable<Utilities> {
return this.http.get<Utilities>('./assets/utilities.json');
}
}
The Json that is has the following content:
{
"Provinces":["East","North West","North"]
}
When I try that, I have the following error:
TypeError: Cannot read property 'Provinces' of undefined.
The thing is, when I remove [formControl]= "province" (change)="getSelectedProvinces()", at least I am able to display the provinces on my page.
How can I go about this?

I finally solved my problem using this code below:
<div class="content">
<label class="label">Province</label>
<div class="form-check form-check-inline" *ngFor="let province of utilities.Provinces">
<label class="form-check-label" for="{{province}}">{{province}}</label>
<input class="form-check-input" (change)="onChangeCategory(province, $event.target.checked)"name="{{ province}}" type="checkbox" id="{{province}}">
</div>
In my .ts, I have the following:
onChangeProvince(province: string, isChecked: boolean) {
if (isChecked) {
this.selectedProvinces.push(province);
} else {
const index = this.selectedProvinces.indexOf(province);
this.selectedProvinces.splice(index, 1);
}
console.log(this.selectedProvinces);
}

Related

My codes are not doing get,set,post so what is my codes error how can i fix it?

these are my .ts codes i write these becasue i want to get product details and delete
import { Component, OnInit } from '#angular/core';
import {FormGroup,FormBuilder, FormControl, Validators} from "#angular/forms"
import { ToastrService } from 'ngx-toastr';
import { Product } from 'src/app/models/product';
import { ProductService } from 'src/app/services/product.service';
import { LocalStorageService } from 'src/app/services/local-storage.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-product-delete',
templateUrl: './product-delete.component.html',
styleUrls: ['./product-delete.component.css']
})
export class ProductDeleteComponent implements OnInit {
products: Product[] = [];
dataLoaded = false;
deleteProductForm:FormGroup;
product :Product
productId :number;
constructor(private formBuilder:FormBuilder,
private productService:ProductService
, private toastrService:ToastrService
,private router:Router,
private localStorageService:LocalStorageService) { }
ngOnInit(): void {
this.createdeleteProductForm();
}
createdeleteProductForm(){
this.deleteProductForm = this.formBuilder.group({
productId:["", Validators.required],
})
}
getbyid() {
Number(localStorage)
Number(this.productService)
this.productService.getbyid(Number(localStorage.getItem("productId"))).subscribe(
(response) => {
this.products = response.data;
this.dataLoaded = true;
this.deleteProductForm.setValue({
productId: this.product,
categoryId: this.product.categoryId,
productName: this.product.productName,
unitPrice: this.product.unitPrice
});
},
(responseError) => {
this.toastrService.error(responseError.error);
}
)
}
deleteProduct() {
if (this.deleteProductForm.valid) {
let productModel = Object.assign({}, this.deleteProductForm.value);
productModel.productId=parseInt(productModel.productId);
this.productService.delete(productModel).subscribe(
(response) => {
this.toastrService.success('Lütfen tekrar giriş yapınız');
this.router.navigate(['/login']);
},
(responseError) => {
this.toastrService.error(responseError.error);
}
);
} else {
this.toastrService.error('Bir hata oluştu.');
}
}
}
these are my html codes i trying to do when user sign in a productId after that click the button delete the product in that ıd
<div class="card">
<div class="card-header"><h5 class="title">Ürün Sil</h5></div>
<div class="card-body">
<form [formGroup]="deleteProductForm">
<div class="mb-3">
<label for="productId">ÜrünId'si</label>
<div class="form-group">
<input type="number"
id="productId"
formControlName="productId" class="form-control"
placeholder="productId"/>
</div>
<div class="card-footer" style="background-color: rgb(4, 62, 255)">
<button
class="btn btn-lg btn-outline-success float-end"
(click)="deleteProduct()"
>
Sils
</button>
</div>
and these are my service
delete(product:Product):Observable<ResponseModel>{
let newPath = this.apiUrl + 'products/delete';
return this.httpClient.post<ResponseModel>(newPath, product );
}
getbyid(productId:number) : Observable<ListResponseModel<Product>> {
let newPath = this.apiUrl + 'products/getbyid?productId=' + productId;
return this.httpClient.get<ListResponseModel<Product>>(newPath);
}
what i'm going for is that when the user goes on a productId click the button, I want to delete the data including the Id first, but what's the null time on main at the moment?
note:Value cannot be null. says back-end
in html POST https://localhost:44314/api/products/delete
[HTTP/2 500 Internal Server Error 9591ms gives this error
First of all, have you checked the value of product in the call of delete ?
Also, maybe it's the httpClient.delete you need since it's the best way to delete an object to the back end. I suggest this:
https://angular.io/guide/http#making-a-delete-request

Angular autocomplete is not working MySQL API

we tried Autocomplete in angular using codeigniter3 controller as a api. but it not reflected in the angular home page.
Autoserivce.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root',
})
export class AutoService {
private baseURL = 'http://localhost/travelgate/api/item';
constructor(private http: HttpClient) {}
getData() {
return this.http.get(this.baseURL);
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { AutoService } from './auto.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
title = 'ng-auto-complete';
posts!: any;
name: any;
constructor(private service: AutoService) {}
ngOnInit() {
this.getAllData();
}
getAllData() {
this.service.getData().subscribe((res: any) => {
this.posts = res;
console.log(this.posts);
});
}
nameValue(name: any) {
this.name = name;
console.log(this.name);
}
}
app.Component.html
<div class="container">
<div class="row">
<div class="col-md-12">
<form class="form mt-5">
<label for="exampleDataList" class="form-label">Datalist example</label>
<input class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search..."
(change)="nameValue($any($event.target).value)">
<datalist id="datalistOptions">
<option *ngFor="let post of posts" [value]="post.name">
</datalist>
</form>
</div>
</div>
</div>
item.php
<?php
require APPPATH . 'libraries/REST_Controller.php';
class Item extends REST_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function index_get($search = 0)
{
if(!empty($name)){
$this->db->select('*');
$this->db->from('rezlive_hotels_city_list');
$this->db->like('name', $name);
$data = $this->db->get()->result_array();
}else{
$query = $this->db->get("rezlive_hotels_city_list");
$resultList=$query->result_array();
$data= json_encode($resultList);
}
$this->response($data, REST_Controller::HTTP_OK);
}
}
screenshot

Angular: Fill Dropdown with Database

I'm new in coding and wanted to make a small Raid Planner.
Now I try to fill my Dropdown with the Raidnames from my database and could need some help with this step. I have problems with adding the data in a dropdownlist.
raid.service.ts
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { RaidItem } from 'src/app/classes/raid-item';
import { environment } from './../environments/environment';
import { publishReplay, refCount } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class RaidService {
constructor(private httpClient: HttpClient) { }
private raidApiUrl = environment.webApiBaseUrl + '/api/Raid/';
getRaids(): Observable < RaidItem[] > {
return this.httpClient.get < RaidItem[] > (this.raidApiUrl + 'GetRaids').pipe(
publishReplay(1),
refCount());
}
}
raid.item.ts
export class RaidItem {
Id: number;
Name: string;
}
edit.component.ts
import { Component, OnInit } from '#angular/core';
import { NgbDateStruct, NgbCalendar } from '#ng-bootstrap/ng-bootstrap';
import { NgbDateStructAdapter } from '#ng-bootstrap/ng-bootstrap/datepicker/adapters/ngb-date-adapter';
import { NgbTimeStruct } from '#ng-bootstrap/ng-bootstrap';
import { RaidService } from 'src/services/raid.service';
import { RaidItem } from '../classes/raid-item';
#Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
time = {hour: 13, minute: 30, second: 0};
hourStep = 1;
minuteStep = 15;
model: NgbDateStruct;
date: {year: number, month: number};
raidItems: RaidItem[] = [];
constructor(private calendar: NgbCalendar, private raidService: RaidService) { }
ngOnInit() {
this.raidService.getRaids().subscribe(raidResult => {
this.raidItems = raidResult;
});
}
selectToday() {
this.model = this.calendar.getToday();
}
onSubmit() {
}
}
edit.component.html
With this step I have the most problems. Don't know exactly how to get the raidnames into the dropdown
<div class="container1">
<ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next"></ngb-datepicker>
</div>
<div class="container2">
<ngb-timepicker [(ngModel)]="time" [seconds]="false"
[hourStep]="hourStep" [minuteStep]="minuteStep" [secondStep]="00"></ngb-timepicker>
</div>
<select formControlName="raids" id="raids">
<option *ngFor="let RaidItem of getRaids(); let i = index" [value]="getRaids[i].Name">
{{getRaids[i].Name}}
</option>
</select>
You already stored your output in raidItems inside the compoent. SO don't need to call function from template. Use variable to construct the loop.
<option *ngFor="let raidItem of raidItems" [value]="raidItem.Name">
{{raidItem.Name}}
</option>
NgFor already provides alias to each iteration, which in your case is RaidItem. getRaids is a method, but you tried to use it like a variable.
This should work:
<select formControlName="raids" id="raids">
<option *ngFor="let RaidItem of getRaids(); let i = index" [value]="RaidItem.Id">
{{RaidItem.Name}}
</option>
</select>

Angular, Displays a list multiple times on the same html page, that is updated each round of the loop through c#

I want to display a list as the options in select when in each round in the loop the list will be updated according to the current div
It works in terms of concept, but the html is updated only once according to the last entry in the list and does not display a different list for each loop rotation
my html
<div *ngFor="let item of listConstraint" [value]="item.id">
<p>{{item.name_constraint}}</p>
<select>
<option *ngFor="let item1 of listConstraintDetails" [value]="item1.id">
{{item1.name_constraint}}</option>
</select>
</div>
my ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import { AjaxRequestService } from 'src/app/services/Request/ajax-request.service';
import { ConstraintKind } from 'src/app/class/constraintKind';
import { ConstraintDetails } from 'src/app/class/constraint-details';
#Component({
selector: 'app-constraints',
templateUrl: './constraints.component.html',
styleUrls: ['./constraints.component.css']
})
export class ConstraintsComponent implements OnInit {
constraintForm: FormGroup;
listConstraint: ConstraintKind[] = [];
listConstraintDetails: ConstraintDetails[] = [];
constructor(private http: AjaxRequestService, private httpClient: HttpClient, private route: Router) {
}
ngOnInit(): void {
this.GetConstraintsKind();
}
GetConstraintsKind() {
return this.http.GetConstraintsKind().subscribe(data => {
this.listConstraint = data;
data.forEach(element => {
this.GetConstraintsDetails(element.id);
})
console.log(data);
})
}
GetConstraintsDetails(constraintId) {
return this.http.GetConstraintsDetails(constraintId).subscribe(data => {
this.listConstraintDetails = data;
console.log(data);
})
}
}
my functions ajax service
GetConstraintsKind() {
return this.http.get<any>('http://localhost:11818/Api/Constraint/getConstraintKind', { headers: this.header });
}
GetConstraintsDetails(constraintId: number) {
return this.http.get<ConstraintDetails[]>('http://localhost:11818/Api/Constraint/GetConstraintsDetails/' + constraintId);
}
the server works well, and send the correct data, but the html display the same list the whole time
Thanks so much for any help
You are performing inner loop operation all at ngOnInit inside a single array, thats overwriting previously fetched data in the listConstraintDetails array.
What you want can be achieved, if you modify your code a little, like this
ngOnInit(): void {
this.GetConstraintsKind();
}
GetConstraintsKind() {
return this.http.GetConstraintsKind().subscribe(data => {
this.listConstraint = data;
})
}
GetConstraintsDetails(constraintId):ConstraintDetails[]{
let itemsarr: ConstraintDetails[] = [];
if(constraintId)
{
this.http.GetConstraintsDetails(constraintId).subscribe(data => {
itemsarr = data;
})
}
return itemsarr;
}
And your html would get modified like
<div *ngFor="let item of listConstraint" [value]="item.id">
<p>{{item.name_constraint}}</p>
<select>
<option *ngFor="let item1 of GetConstraintsDetails(item.id)" [value]="item1.id">
{{item1.name_constraint}}</option>
</select>
</div>
Thanks.
my html
<div *ngFor="let item of listConstraint" [attr.data-value]="item.id">
<p>{{item.name_constraint}}</p>
<select *ngIf="constraintDetails[item.id]">
<option *ngFor="let item1 of constraintDetails[item.id]" [value]="item1.id">
{{item1.name_constraint}}</option>
</select>
</div>
my ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import { AjaxRequestService } from 'src/app/services/Request/ajax-request.service';
import { ConstraintKind } from 'src/app/class/constraintKind';
import { ConstraintDetails } from 'src/app/class/constraint-details';
import { Observable } from 'rxjs';
#Component({
selector: 'app-constraints',
templateUrl: './constraints.component.html',
styleUrls: ['./constraints.component.css']
})
export class ConstraintsComponent implements OnInit {
constraintForm: FormGroup;
listConstraint: ConstraintKind[] = [];
listConstraintDetails: ConstraintDetails[] = [];
constraintDetails = {};
constructor(private http: AjaxRequestService, private httpClient: HttpClient, private route: Router) {
}
ngOnInit(): void {
this.GetConstraintsKind();
}
GetConstraintsKind() {
return this.http.GetConstraintsKind().subscribe(data => {
this.listConstraint = data;
for (let i = 0; i < this.listConstraint.length; i++) {
const element = this.listConstraint[i].id;
this.http.GetConstraintsDetails(element)
.subscribe(cd => {
this.constraintDetails[element] = cd;
console.log(this.constraintDetails)
});
}
})
}
GetConstraintsDetails(constraintId): ConstraintDetails[] {
console.log(constraintId);
let itemsarr: ConstraintDetails[] = [];
if (!itemsarr) {
this.http.GetConstraintsDetails(constraintId).subscribe(data => {
itemsarr = data;
})
}
return itemsarr;
}
}

Json data to be represented in formcontrol in angular 5

I am trying to bind the Json value which I get from my server to respective textboxes,but when I bind I see the value in textbox as [object object]
<h1>{{title}}</h1>
<h3>Catalog</h3>
<hr />
<fieldset>
<legend>About Tool</legend>
<form [formGroup]="CatalogForm" #formDir="ngForm" novalidate>
<div class="form-group row">
<!-- <div *ngIf="ItemName != null"></div>-->
<!--<div *ngFor="let c of CatalogForm;let i=index"></div>-->
<label class="control-label col-md-12">ItemName</label>
<div class="col-md-4"></div>
<input class="form-control" readonly="true" type="text" formControlName="Category" >
<pre>{{CatalogForm.value.Category | json }}</pre>
</div>
<br /><br/>
</form>
</form>
and my component code is
import { Component, OnInit } from '#angular/core';
import { Http, Headers } from '#angular/http';
import { FormsModule,NgForm, FormBuilder, FormGroup, Validators, FormControl } from '#angular/forms';
import { Router, ActivatedRoute } from '#angular/router';
import { CatalogComponent } from '../catalog/catalog.component';
import { CatalogService } from '../services/Catalog.service';
import { ContactService } from '../services/Contact.service';
import { URLService } from '../services/URL.service';
import { SupportService } from '../services/Support.service';
import { Catalog } from '../classes/Catalog';
import { Contact } from '../classes/Contact';
import { URL } from '../classes/URL';
import { Support } from '../classes/Support';
import { Category } from '../classes/Category';
#Component({
selector: 'app-catalog-form',
templateUrl: './catalog-form.component.html',
styleUrls: ['./catalog-form.component.scss']
})
export class CatalogFormComponent implements OnInit {
Catalogdata:Catalog;
Contacts:Contact[];
URLs:URL[];
Supportdata:Support[];
CatalogForm:FormGroup;
title: string = "";
id: number;
errorMessage: any;
constructor( private _fb: FormBuilder,private _avRoute: ActivatedRoute,
private catService: CatalogService,private conservice:ContactService,
private urlservice:URLService,private supservice:SupportService, private _router: Router) {
if (this._avRoute.snapshot.params["id"]) {
this.id = this._avRoute.snapshot.params["id"];
}
this.CatalogForm = this._fb.group({
Category: [''],
SubCategory:[''],
ItemName:[''],
Description:[''],
IAP_Number:[''],
/*ToolOwner:[''],
BusinessOwner:[''],
ProdURL:[''],
IncidentURL:[''],
RequestURL:[''],
SupportType:[''],
SupportValue:[''],
SupportLink:['']*/
})
}
ngOnInit() {
console.log("I am in form component",this.id);
if (this.id > 0) {
this.title = "View";
console.log("Title of form:",this.title) ;
this.catService.getCatalogDetails(this.id)
.subscribe( t =>
this.CatalogForm.patchValue
({Category:t,SubCategory:t,Description:t,ItemName:t,IAP_Number:t}) , err =>
console.log("Error messgae:",this.errorMessage)
);
}
console.log("Catalog and Category Details:",this.CatalogForm);
//.controls.Category.
//get(['cItem']));
}
cancel() {
this._router.navigate(['/home']);
}
//get ItemName() {return this.CatalogForm.get('Category').value; }
}
The <pre>{{CatalogForm.value.Category | json }}</pre>
gives me below data in JSON
[
{
"cats": {
"category_Id": 3,
"category_Name": "abc",
"sub_Category": "mmm"
},
"cItem": {
"catalog_Item_Id": 1,
"category_Id": 3,
"item_Name": "hsdd",
"description": "sadss",
"popularity_Flag": true,
"iaP_No": null,
"categoryID": {
"category_Id": 3,
"category_Name": "sds",
"sub_Category": "sad"
}
}
}
]
My problem is how to show the category_Name valuein a textbox.Here the json has category_name as abc and I want to bind that value to category_name textbox as its value. can you take a look?
Try:
<input
class="form-control"
readonly="true"
type="text"
formControlName="Category"
[ngModel]="CatalogForm.value.Category[0].cats.category_Name">
Use [(ngModel)] for 2 way binding