#jquery #angular #forms #events #rxjs
Вопрос:
всякий раз, когда событие вставки происходит в поле ввода, оно не загружает параметры в список данных с первой попытки, но со второй попытки оно работает и позволяет кнопке продолжить.Также он отлично работает в ключевом событии.
ngb-tab>
<ng-template ngbTabTitle>Move </ng-template>
<ng-template ngbTabContent>
<div class="form-asset">
<div class="col-md-12">
<div class="form-group is-assets label-floating">
<label class="control-label lable-top">
Select Asset<span>*</span>
</label>
<input type="text" class="form-control" (input)="search($event)" list="exampleList"
placeholder="Choose Q## Heading ##R code *">
*emphasized text*Here Data uploads on loading of component
<datalist id="exampleList">
<option [value]="qr?.qr_code" *ngFor="let qr of items">
{{qr?.qr_code}}</option>
</datalist>
</div>
</div>
<div class="col-md-12">
<!-- </div> -->
<h4 class="red-heading" style="margin: 0;">Select Dropoff</h4>
<div class="table-responsive">
<table id="allLocationsDatatablesModal" class="table table-striped table-dropoff">
<thead>
<tr>
<th>Action</th>
<th>{{'locations.Num' | translate}}</th>
<th>ID</th>
<th>{{'locations.contactPerson' | translate}}</th>
<th>Phone No.</th>
<th>{{'locations.phone1' | translate}}</th>
</tr>
</thead>
</table>
</div>
</div>
<p class="text-center">
<button [disabled]="!selectedLocations.length || !movedAseetSourceId"
(click)="onAssetMovementSubmit()" class="btn btn-danger" type="submit">Move Asset</button>
</p>
</div>
</ng-template>
</ngb-tab>
import { Component, OnInit, Input, ViewEncapsulation, AfterViewInit, ViewChild, TemplateRef, HostListener } from "@angular/core";
import { UserService, AlertService } from "@app/services";
import Utils from "@app/shared/utils";
import { NgbActiveModal, NgbDateStruct, NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { Assets, MoveAssets } from "./asset.model";
import { NgForm } from "@angular/forms";
import { JobPickupDropoffComponent } from "@app/shared";
import { EditLocationAssetComponent } from "../editLocationAsset/edit-location-asset.component";
import { Subject } from "rxjs";
declare var swal: any;
declare var $: any;
@Component({
selector: 'app-view-assets',
templateUrl: './viewAssets.component.html',
styleUrls: ['./viewAssets.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ViewAssetsComponent implements OnInit, AfterViewInit {
@Input() locationObj;
loading: boolean;
model: NgbDateStruct;
asset: Assets = new Assets();
datatable: any;
timeout: any;
datatableRemoved: any;
timeoutRemoved: any;
datatableMoveAssets: any;
timeoutMoveAssets: any;
selectedPickups: any = [];
locationsList: any;
selectedLocations: any = [];
**movedAseetSourceId: string = '';**
moveAsset = new MoveAssets();
activeAssets: any;
items: any;
**searchValue: string='';
private searchTerms = new Subject<string>();**
constructor(
private userService: UserService,
private alertService: AlertService,
public activeModal: NgbActiveModal,
private modalService: NgbModal
) { }
// changes are detected in Oninit
**ngOnInit() {
this.searchTerms.debounceTime(250).distinctUntilChanged()
.subscribe(filterQr=> {
this.searchValue = filterQr;
if(this.searchValue){
this.getQRCode()
}
});
}**
ngAfterViewInit() {
this.drawDatatableActiveAssets();
this.drawDatatableRemovedAssets();
this.drawMoveAssetDatatable();
var self = this, row;
$(document).on('input', ".checkbox-location", this.onSelect);
$('#activeAssets').on('click', '[title="Remove Asset"]', function (event) {
if (self.datatable.row(this).data() !== undefined) {
row = self.datatable.row(this).data().id;
}
else {
row = self.datatable.row($(this).parent('td').parent('tr')).data().id
}
// if(window.outerWidth > 800) row = self.datatable.row($(this).parent('tr')).data().id;
// if(window.outerWidth < 800) row = self.datatable.row(this).data().id;
self.deleteAssetsQR(row);
});
$('#activeAssets').on('click', '[title="Edit Asset"]', function (event) {
self.closeModal()
let assetData;
if (self.datatable.row(this).data() !== undefined) {
assetData = self.datatable.row(this).data()
}
else {
assetData = self.datatable.row($(this).parent('td').parent('tr')).data()
}
const modalRef = self.modalService.open(EditLocationAssetComponent, {
size: "lg",
backdrop: "static",
windowClass: "modal-lg-class",
});
modalRef.componentInstance.assetData = assetData;
modalRef.componentInstance.address = self.locationObj;
modalRef.result.then((result) => {
if (!result) {
self.datatable.ajax.reload();
} else {
const modalRef = self.modalService.open(ViewAssetsComponent, {
size: "lg",
backdrop: "static",
windowClass: "modal-lg-class",
});
modalRef.componentInstance.locationObj = resu<
modalRef.result.then((result) => {
if (result) {
self.datatable.ajax.reload();
}
});
}
});
})
}
onAssetMovementSubmit() {
this.moveAsset.dest_address_uid = this.selectedLocations[0].id;
this.moveAsset.src_address_uid = this.locationObj.id;
this.moveAsset.qr_code = this.movedAseetSourceId;
this.userService.moveAssetLocation(this.moveAsset).subscribe((response: any) => {
if (response.status === 'Success') {
this.alertService.success('Asset Moved successfully.');
this.selectedLocations.length = 0;
this.movedAseetSourceId = '';
this.activeModal.close();
} else {
this.alertService.error(response.error.error_message[0]);
}
});
}
onSubmit(addForm: NgForm) {
this.asset.address_uid = this.locationObj.id;
this.asset.arrival_date = this.model ? `${(this.model.year)}/${(this.model.month < 10 ? '0' : '') this.model.month}/${(this.model.day < 10 ? '0' : '') this.model.day}` : null;
this.userService.createLocationAssets(this.asset).subscribe((response: any) => {
if (response.status === 'Success') {
this.alertService.success('Asset Added successfully.');
addForm.form.reset();
this.activeModal.close();
} else {
this.alertService.error(response.error.error_message[0]);
}
});
}
deleteAssetsQR(id) {
swal({
title: 'Are you sure',
text: 'Do you want to remove asset?',
type: 'warning',
showCancelButton: true,
cancelButtonClass: 'btn btn-danger',
confirmButtonClass: 'btn btn-success',
buttonsStyling: false,
cancelButtonText: 'No',
confirmButtonText: 'Yes'
}).then((result) => {
this.userService.deleteLocationAssets(id).subscribe((response: any) => {
if (response.status === 'Success') {
this.datatable.ajax.reload()
this.alertService.success(response.data[0]);
} else {
this.alertService.error(response.error.error_message[0]);
}
})
}).catch(swal.noop)
}
drawDatatableRemovedAssets() {
const options = {
serverSide: true,
columns: [
{
data: 'qr_code',
},
{
data: null,
render: (data) => {
return this.formatDateOnly(data.created_at)
}
},
{
data: null,
render: (data) => {
return this.formatDateOnly(data.deleted_at)
}
},
{
data: null,
render: (data) => {
return (data.asset_type || '')
}
},
{
data: null,
render: (data) => {
return (data.brand || '')
}
},
{
data: null,
render: (data) => {
return (data.model_number || '')
}
}
],
deferRender: true,
"bAutoWidth": false,
"ordering": false,
"bLengthChange": false,
searching: false,
ajax: (data, callback) => {
let page = this.datatable !== undefined ? this.datatable.page.info().page 1 : 1;
let perPage = this.datatable !== undefined ? this.datatable.page.info().length : 10;
if (this.timeoutRemoved) {
clearTimeout(this.timeoutRemoved);
}
this.timeoutRemoved = setTimeout(() => {
this.loading = true;
this.userService.getDeletedLocationAssets({ page: page, per_page: perPage, address: this.locationObj.id, mode: '' })
.map(_ => _.data)
.subscribe(res => {
var resData = res[0];
callback({
draw: data.draw,
data: resData.data,
recordsTotal: resData.total,
recordsFiltered: resData.total
});
this.loading = false;
});
}, 1000);
}
};
this.datatableRemoved = $('#removed-assets').DataTable(options);
}
drawDatatableActiveAssets() {
const options = {
serverSide: true,
columns: [
{
data: 'qr_code',
},
{
data: null,
render: (data) => {
return this.formatDate(data.created_at)
}
},
{
data: null,
render: (data) => {
if (data.moved_from amp;amp; data.moved_from.length) {
data = (data.moved_from[0] amp;amp; data.moved_from[0].source_address amp;amp; data.moved_from[0].source_address.id_number || '') '-' (data.moved_from[0] amp;amp; data.moved_from[0].source_address amp;amp; data.moved_from[0].source_address.company_name || '')
}
else {
data = 'System';
}
return data;
}
},
{
data: null,
render: (data) => {
return this.formatDateOnly(data.arrival_date)
}
},
{
data: null,
'render': function (data) {
data = `<button class="btn btn-success btn-xs" title="Edit Asset" style="color: #fff; margin:0 5px !important; padding:5px"><i class="material-icons">edit</i></button>
<button class="btn btn-danger btn-xs" title="Remove Asset" style=" color: #fff; margin:0 5px !important; padding:5px"><i class="material-icons">close</i></button>
`;
return data;
}
},
{
data: null,
render: (data) => {
return (data.asset_type || '')
}
},
{
data: null,
render: (data) => {
return (data.brand || '')
}
},
{
data: null,
render: (data) => {
return (data.model_number || '')
}
},
],
deferRender: true,
"bAutoWidth": false,
"ordering": false,
"bLengthChange": false,
scrollCollapse: true,
searching: false,
columnDefs: [
{ "width": "150px", "targets": 0 },
],
responsive: true,
ajax: (data, callback) => {
let page = this.datatable !== undefined ? this.datatable.page.info().page 1 : 1;
let perPage = this.datatable !== undefined ? this.datatable.page.info().length : 10;
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = setTimeout(() => {
this.loading = true;
this.userService.getLocationAssets({ page: page, per_page: perPage, address: this.locationObj.id, mode: '' })
.map(_ => _.data)
.subscribe(res => {
var resData = res[0];
this.activeAssets = res[0].data;
// this.items = this.activeAssets;
callback({
draw: data.draw,
data: resData.data,
recordsTotal: resData.total,
recordsFiltered: resData.total
});
this.loading = false;
});
}, 1000);
}
};
this.datatable = $('#activeAssets').DataTable(options);
}
drawMoveAssetDatatable() {
const options = {
data: this.locationsList,
columns: [
{
data: null,
render: function (data) {
return `<span class="radio">
<label><input value="${data.id}" name="select-location" class="checkbox-location" type="radio"></label>
</span>`;
}
},
{ data: 'num' },
{ data: 'id_number' },
{ data: 'company_name' },
{ data: 'phone_number' },
{
data: null,
'render': function (data) {
let no_second_number = (data.second_number != null) ? data.second_number : ' N/A '
return no_second_number
}
},
],
serverSide: true,
deferRender: true,
"bAutoWidth": false,
"bLengthChange": false,
searching: true,
ajax: (data, callback) => {
let page = (this.datatableMoveAssets !== undefined) ? this.datatableMoveAssets.page.info().page 1 : 1;
if (this.timeoutMoveAssets) {
clearTimeout(this.timeoutMoveAssets);
}
this.timeoutMoveAssets = setTimeout(() => {
this.loading = true;
this.userService.getLocations(page, data.length, data.search.value)
.map(_ => _.data)
.subscribe(res => {
let resData = res[0];
callback({
draw: data.draw,
data: resData.data,
recordsTotal: resData.total,
recordsFiltered: resData.total
});
this.loading = false;
});
}, 1000);
}
};
this.datatableMoveAssets = $('#allLocationsDatatablesModal').DataTable(options);
}
//this method is called when we have search value greater than 3
**getQRCode(){
if(this.searchValue.length>=3){
this.userService.getLocationOptions({address: this.locationObj.id, mode: 'all',query:this.searchValue})
.map(_ => _.data)
.subscribe(data=>{
// here data is feeding to the datalist tag in html
this.items=data
if(this.items){
this.filterItem(this.searchValue)
}
})
}
}**
// this functions calls on input change
**search(event) {
this.searchTerms.next(event.target.value);
}**
// this method is creating issue, it is not getting data from in opts variable
**filterItem(event) {
this.movedAseetSourceId = null;
if(document.getElementById('exampleList')){
var opts = document.getElementById('exampleList').childNodes;
if(opts){
for (var i = 0; i < opts.length; i ) {
if ((<HTMLInputElement>(opts[i])).value === event) {
this.movedAseetSourceId = event;
break;
}
}
}
}
}**
onSelect = (event) => {
const selected = this.datatableMoveAssets.row($(event.target).parents('tr')).data();
this.selectedLocations = [selected];
// this.drawDatatable();
}
formatDate(date: string) {
return Utils.transform(date);
}
formatDateOnly(date: string) {
return Utils.transformDateOnly(date);
}
closeModal() {
this.activeModal.close(false);
}
}
событие вставки не заполняет список данных при первой вставке, но при второй попытке оно заполняет значения параметров, чтобы кнопка была включена