Values from API not getting appended to Angular2 Dropdown - javascript

I have the following project flow structure:
import_product.html
<div class="row custom_row">
<div class="col-md-2">Additional Duty: </div>
<div class="col-md-2">
<select class="form-control" [(ngModel)]="product.additional_duty_not_no" (change)="changeAddDutyNotSrNo()" required="required">
<option value=" ">-- SELECT --</option>
<option *ngFor="let add_duty_not_no_data of product.addl_duty_not_nos" value="{{ addl_duty_not_no_data.notification_no }}">{{ addl_duty_not_no_data.notification_no }}</option>
</select>
</div>
import_product_component.ts
getAddlNotificationDuty() {
var url = 'api/getBasicNotificationDuty';
var add_duty_not_no_data : any;
var ref = this;
this.jobService.loadRemoteUrl(url)
.subscribe(
data => { add_duty_not_no_data = data},
err => console.error(err),
() => {
if (add_duty_not_no_data.length > 0) {
ref.product.addl_duty_not_nos = add_duty_not_no_data;
}
}
);
}
Now the call is made to the API backend powered by Laravel PHP which successfully returns the desired data in the following array format:
[{"notification_no":"012/39"},{"notification_no":"007/97"},{"notification_no":"999/85"}]
But unfortunately the dropdown in the frontend is not getting populated with the concerned values. There are no errors in the console.
console.log till the .ts component shows objects being returned successfully but it is not getting appended to the dropdown.
Please let me know if you want any more details. Any help will be highly appreciated.

where do you get
basic_duty_not_no_data
from?
also I recommend using slightly different flow with handling ajax call
add_duty_not_no_data: any
getAddlNotificationDuty() {
var url = 'api/getBasicNotificationDuty';
this.jobService.loadRemoteUrl(url)
.subscribe(
data => {
if (data.length > 0) {
this.add_duty_not_no_data = data;
}
},
err => console.error(err)
);
}

Related

Not able to display drop down list in reactjs

My API is returning below result.
I have below code to display in list.
const [result,setResult] = useState([]);
const fetchStatus = async ()=>{
await httpClient.get( config.resourceServerUrl+"/certificates/status").then(res=>{
setResult(res.data);
setActive(true);
alert(result);
})
and I am displaying list like below.
<div className="col-md-4">
<label htmlFor="status">Status</label>
<select
name="requestStatus"
style={{ display: 'block' }}>
<option value="" selected >
Please Select the Status
</option>
{
active && result.map((sts:any)=>{
<option key="" value="">
{sts}
</option>
})
}
</select>
though there is no error but it is not displaying anything.
Its because you've got {} around your JSX, should be ()
active && result.map((sts:any) => (
<option>{sts}</option>
))
or you can do
active && result.map((sts:any) => {
return (
<option>{sts}</option>
)
})
I don't believe you await httpClient.get. The .then will be called when the get completes.
you are setting the dropdown to each object in the returned array. You want to set it to the value of the request_status key: sts.request_status
set the key attribute for elements you create using map
{
active && result.map((sts:any)=>{
{sts.request_status}
})
}

Duplicate users(entries) should not be add in table

I'm facing an issue. i have a dropdown contains list of users fetching from database. When i select a user from dropdown it appends on below table and when i select the same user again it again appends on below table as a new row. So i want to stop duplicating same user in table.
Here's my View Code
<div class="form-group col-md-4 " style="display:none" id="user-container">
<label>User</label>
<select id="users" class="form-control" disabled="disabled">
<option value="">Select User</option>
</select>
<p class="validate-error"><span id="users_error"></span></p>
</div>
Here's my JavaScript Code
PostMyData(obj, '/Admin/Meetings/GetUserGroupUsers', (res) => {
if (res.Code === 0 || res.Code === -1) {
alert(res.Message);
}
if (res.Code === 1) {
$('#users').html('');
$('#users').append('<option value="">Select User</option>');
res.Data.map(item => {
$('#users').append(`<option value="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
$('#users').prop('disabled', false);
}
I think dynamically giving an id will do this job.Lets say you are giving giving id based of id value, then you can easily find if same id exits or not.
PostMyData(obj, '/Admin/Meetings/GetUserGroupUsers', (res) => {
users = document.getElementById("users");
if (res.Code === 0 || res.Code === -1) {
alert(res.Message);
}
if (res.Code === 1) {
users.html('');
users.append('<option value="">Select User</option>');
res.Data.map(item => {
if(!users.querySelector(item.UserId))
users.append(`<option value="${item.UserId}" id="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
users.prop('disabled', false);
}
I don't know what do you mean by duplicating same user in table, If you mean you want prevent duplicating user in the dropDown list you can try on this code, if not, please provide more details about the table you are working on.
...
const usersList= $('#users');
res.Data.forEach(item => {
if(usersList.find(`option[value=${item.UserId}]`).length > 0){
return ; // do nothing
}
usersList.append(`<option value="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
...

What should I use to get my updated count based on filter selection?

I am using CSV upload and display the data in the table along with using custom table filter pipe function.
How can I get the count of filtered based on filter section?
For e.g. Once you upload data considering your csv has 7 rows; it would be Showing 7 of 7 Records.
When you are filtering based on Gender male/female I should get Showing 4 of 7 Records or Showing 3 of 7 Records
I tried below I didn't get the results.
Showing {{filteredUsers.length}} of {{dataList.length}} Records
If I am doing like:
<strong class="ml-3" *ngFor="let record of dataList | tableFilter: form.value as filteredUsers">
Showing {{filteredUsers.length}} of {{dataList.length}} Records
</strong>
I am getting the count n updating as well based on the filter selection but it's repeating based on the number of rows so, coming 7 times.
app.component.html
<form #form="ngForm">
<select class="form-control form-control-sm" name="gender" ngModel>
<option value="" selected>All</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</form>
<tr *ngFor="let record of dataList | tableFilter: form.value as filteredUsers">
<td> {{record.name}} </td>
<td> {{record.gender}} </td>
</tr>
Live: https://stackblitz.com/edit/angular-csv-parser-aazvnq?file=app%2Fapp.component.html
CSV Sample
I suggest a slightly different approach than Nicholas's solution - instead of updating two items every time a change is made, you can have the pipe function update the variable which represents the count - this way, a single place is responsible of handling both the count and the filtering, this requires adding an object in the component:
countObj = { count: 0 };
in the template:
Showing {{countObj.count}} Records
...
<tr *ngFor="let record of dataList | tableFilter: form.value:countObj">
and in the transform function:
transform(list: any[], filters: Object, countObj: any) {
const keys = Object.keys(filters).filter(key => filters[key]);
const filterUser = user => keys.every(key => user[key] === filters[key]);
if (keys.length) {
const res = list.filter(filterUser);
countObj.count = res.length;
return res;
} else {
countObj.count = list.length;
return list;
}
}
working stackblitz
Make the following changes:
The basic change added here is introducing another variable selectedCount that will hold the count of selected items based on the dropdown values.
app.component.html
Showing {{selectedCount}} of {{dataList.length}} Records
<div>
<form #form="ngForm">
<select class="form-control form-control-sm" name="gender"
[(ngModel)]="dropDown" (change)="dropDownChange()">
<option value="All">All</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</form>
</div>
app.component.ts
dropDown = "All";
public selectedCount = this.dataList.length;
dropDownChange() {
if (this.dropDown !== "All") {
this.selectedCount = this.dataList.filter(
e => e.gender === this.dropDown
).length;
} else {
this.selectedCount = this.dataList.length;
}
}
table.filter.pipe.ts
export class TableFilterPipe implements PipeTransform {
transform(list: any[], filters: any) {
if (filters.gender !== "All") {
const keys = Object.keys(filters).filter(key => filters[key]);
const filterUser = user => keys.every(key => user[key] === filters[key]);
return keys.length ? list.filter(filterUser) : list;
} else {
return list;
}
}
}
Working stackblitz found here.

Mean stack: display products into ng smart table

Im trying to display the product data using ng2-smart-table plugin.
I am able to get the products in the browser log, but i need to display the same onChange of a drop down value.
\app\components\layout\blank-page\blank-page.component.html
<form role="form">
<fieldset class="form-group">
<label>Select Category</label><br/><br/>
<select [(ngModel)]="selectedObject" (ngModelChange)="onChange(selectedObject)" name="selectedObject" class="form-control">
<option>--Select Category--</option>
<option *ngFor="let category of categories" [value]="category._id">{{category.category_name}}</option>
</select>
</fieldset>
</form>
//This is where table data is displaying, need to show my data here
<ng2-smart-table [settings]="view_update_items_settings" [source]="view_update_items_smart_data" (userRowSelect)="onUserRowSelect($event)" class="table table-hover table-striped"></ng2-smart-table>
app\components\layout\blank-page\blank-page.component.ts
onChange(categoryid) {
this.productService.getProductsOncategory(categoryid).subscribe(data => {
if (data.success) {
//this.selectedObject = data.mainProducts;
console.log(data)
console.log('Products obtained');
} else {
console.log('Not obtained!');
}
});
}
app\services\product.service.ts
getProductsOncategory(category_id){
console.log(category_id)
let catUrl="http://10.*.*.*:5000/products/getProductsOncategory"
let headers = new Headers();
headers.append('Content-Type','application/json');
let catIdObj = JSON.stringify({category_id:category_id})
console.log(catIdObj)
return this.http.post(catUrl,catIdObj,{headers:headers})
.map((response:Response)=>response.json())
.do(data=>console.log(JSON.stringify(data)))
.catch(this.handleError);
}
On selection of a value from drop down, i get data posted in my browser, i need to display the same in my ng2-smart-table
Bind "view_update_items_smart_data" with the data you obtain from server.
onChange(categoryid) {
this.productService.getProductsOncategory(categoryid).subscribe(data => {
if (data.success) {
//this.selectedObject = data.mainProducts;
console.log(data)
console.log('Products obtained');
this.view_update_items_smart_data.load(data);
} else {
console.log('Not obtained!');
}
});
}
For more information you can refer to
https://akveo.github.io/ng2-smart-table/#/examples/populate-from-server

Populate dropdown list dynamically in AngularJS

I'm trying to generate dynamic form based on the key of document fields and using ng-if attribute in AngularJS.
Ex:
- If field name is "name|string" then populate textfield
- If field name is "name|select" then populate dropdownlist
- If field name is "name|datepicker" then populate datepicker
Following is the code:
<div class="form-group" ng-repeat="(index, formVal) in providerModelData" ng-if="!$first">
<label>{{mySplit(index,0) | uppercase}}</label>
<div ng-if="!mySplit(index,1)">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'datepicker'">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
</div>
controller:
$scope.mySplit = function(string, nb) {
var array = string.split('|');
return array[nb];
}
textfields are working fine and populating data but I'm facing issue while populating dropdown fields.
Example: I've two dropdown fields in my mongodb document i.e. city|select and state|select
I'm trying to use ng-options to call function by passing index and colName (document name) to populate dropdownlist but its not working.
Following is the code:
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[colName] = response;
});
};
Express:
router.route('/').get(function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query.query);
db.collection(query.colName).aggregate([{
"$group":{
"_id":"$"+query.query
}
}],function (err, docs) {
console.log(docs);
res.json(docs);
});
});
Initially I tried calling function in ng-repeat but it was going into infine loop. Then later I tried ng-init options but it only calls or initialize once which is not working in my case. Here I need to call function dynamically and based on that I want to populate dropdown for different fields.
Any help would be appreciated.
Your view is completely messed up as far I see it you are missing
ng-model
for your select input.
Your JSON is improper its missing , before {'id_':'Arizona'}
Try to get response in your controller and push it to array and make use of that array in your View :
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
var returnArray = [];
alert(JSON.stringify(response));
angular.ForEach(response,function(option){
//parse response and push it to returnArray
returnArray.push(option);
});
return returnArray;
});
}
View :
<div class="form-group">
<select class="form-control" ng-model="selection" ng-options="dropdown._id for dropdown in getDropDownData()">
<option value="">Select</option>
</select>
</div>
Here is the link to Codepen
.
Consider the following solution:
In your controller, set up a variable for the dropdown data:
$scope.dropdownData = {};
Then change your getDropdownData function to:
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
alert(JSON.stringify(response));
$scope.dropdownData[colName] = response; // This will put data into our html file
});
}
And the HTML for your dropdown case should be:
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
I used the notorious ngInit to make the call from getting data for the server. Perhaps there's a better way that I didn't consider. But in any case, the idea is to make the call to the server, and save the data in a way that you can fetch it easily from the view.
Edit
I don't know why, but for some reason this solution doesn't work with ng-options. It does, however, work when using it like this:
<select class="form-control" ng-init="getDropdownData(index,colName)">
<option value="">Select</option>
<option ng-repeat="dropdown in dropdownData[colName]" value="dropdown._id">{{dropdown._id}}</option>
</select>
See a simple example here.
Finally I solved it myself. Thanks #Rishab777 and #yarons for guiding me.
Here's the view code:
<div ng-if="mySplit(index, 1) == 'select'">
<select class="form-control">
<option value="">Select</option>
<option ng-model="providerModelData[index]" ng-selected="providerModelData[index]" ng-repeat="dropdown in dropdownData[index]" value="{{dropdown._id}}">{{dropdown._id}}</option>
</select>
</div>
and controller:
$scope.showModal = false;
$scope.toggleModal = function (colId, colName) {
$http.get('/collectiondata/' + colId + '/collectionName/' + colName).success(function (response) {
$scope.colName = colName;
$scope.colId = colId;
for (var key in response) {
if (response.hasOwnProperty(key)) {
if ($scope.mySplit(key, 1) === 'select') {
$scope.getDropdownData(key, colName);
}
}
}
$scope.providerModelData = response;
$scope.showModal = !$scope.showModal;
});
};
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[query] = response;
});
};
Now the issue is ng-selected="providerModelData[index]" is not working and its showing last item as selected only.

Categories