My date picker is not coming up. want to know What I have missed - datepicker

I am trying to add a datepicker for my mobile app in Native script angular. I used book flight example in Playground as reference. My page is getting blured. My date picker is not coming up. I am new to native script and java script. I am including my code. Please let me know where I have gone wrong.
I may be missing something.
component.html
<GridLayout>
<ScrollView>
<GridLayout>
<StackLayout class="form">
-------
----------
<TextField hint="Start Date" [(ngModel)]="leaveDetails.startDate"
(openSelectDate)="onOpenSelectDate($event)"
[selectedDate]="selectedDate"
[isOnOpenStartDate]="isOnOpenStartDate"
class="input input-border" (tap)="onOpenSelectDate(true)">
</TextField>
<TextField hint="End Date" [(ngModel)]="leaveDetails.endDate"
class="input input-border" (tap)="onOpenSelectDate(false)">
</TextField>
--------
---------
</GridLayout>
</ScrollView>
<GridLayout row="0" col="0" rowSpan="4" colSpan="2" opacity="0"
class="overlay" id="overlayGridLayout"></GridLayout>
<GridLayout row="0" col="0" rowSpan="4" colSpan="2" rows="auto, auto,
auto"
columns="*,*" verticalAlignment="center" visibility="hidden"
opacity="0" class="select-date" id="selectDateGridLayout">
<Label row="0" col="0" colSpan="2" text="Select Date" class="title-
select-date"></Label>
<DatePicker row="1" col="0" colSpan="2" [(ngModel)]="dateSelector"
(dateChange)="onDateChanged($event)" verticalAlignment="center">
</DatePicker>
<Button row="2" col="0" text="Cancel" class="btn-next"
(tap)="onCloseSelectDate(true)"></Button>
<Button row="2" col="1" text="OK" class="btn-previous"
(tap)="onCloseSelectDate(false)"></Button>
</GridLayout>
</GridLayout>
compoment.ts
import { Page } from "tns-core-modules/ui/page";
import { GridLayout } from "tns-core-modules/ui/layouts/grid-layout";
import { Visibility } from "tns-core-modules/ui/enums";
export class CreateleavesComponent {
leaveDetails : LeaveDetails;
public selectedDate: Date;
public isOnOpenStartDate: boolean = false;
public dateSelector = new Date();
private _selectDateGridLayout: GridLayout;
private _overlayGridLayout: GridLayout;
constructor(private router: Router, private page: Page) {
this.leaveDetails = new LeaveDetails();
this.leaveDetails.startDate = new Date();
this.leaveDetails.endDate = new Date();
}
ngOnInit(): void {
this._selectDateGridLayout =
this.page.getViewById('selectDateGridLayout');
this._overlayGridLayout = this.page.getViewById('overlayGridLayout');
}
// Select Date
onOpenSelectDate(event) {
this.isOnOpenStartDate = event;
if (this.isOnOpenStartDate) {
this.dateSelector = this.leaveDetails.startDate || new Date();
} else {
this.dateSelector = this.leaveDetails.endDate || new Date();
}
this._selectDateGridLayout.visibility = <any>Visibility.visible;
this._selectDateGridLayout.className = 'select-date';
this._overlayGridLayout.animate({ opacity: 0.5, duration: 300 });
}
onCloseSelectDate(isCancel: boolean) {
if (!isCancel) {
this.selectedDate = this.dateSelector;
if (this.isOnOpenStartDate) {
this.leaveDetails.startDate = this.dateSelector;
} else {
this.leaveDetails.endDate = this.dateSelector;
}
}
this._selectDateGridLayout.className = 'select-date';
this._overlayGridLayout.animate({ opacity: 0, duration: 300 })
.then(() => {
this._selectDateGridLayout.visibility = <any>Visibility.collapse;
})
.catch(() => {
});
}
onDateChanged(args) {
let date: Date = args.value;
this.dateSelector = date;
}
}
I tried to get pointers from other question/answers but I am not able to fix my issue.
I expect the date picker to come up when I click on the start date text field.
But the datepicker is not coming up.I have displayed selectDateGridLayout in onOpenSelectDate function and it is getting changed from hidden to visible.

Looks like you haven't imported the Datepicker in your component. At the top of that component.ts file put:
import { DatePicker } from "tns-core-modules/ui/date-picker";

Related

mui-datatable - update content of table by click a button possible?

I painstakingly put together a mui-datatable that displays the content of a CSV file.
Now I want to read another CSV file when a button is clicked.
Unfortunately, I'm a complete beginner - and I don't really know how to implement it.
I tried the following - but unfortunately it doesn't work that way.
Can someone help me with that?
As a 2nd step, I want to show a mui-alert for 3 seconds when I click on a cell. At the same time, a filter with the content of the cell is set. I have already successfully implemented this functionality using the setTimeout function. Strangely enough, only if I remove a filter within the 3 seconds "setTimeout" and then add a new filter, both filters (the one already removed and the new filter) are added again. Somehow the "setTimeout" function seems to be blocking further input in the mui-datatable....
Here is my code:
import {
Typography,
AppBar,
Button,
CssBaseline,
Toolbar,
Container,
Grid,
} from "#mui/material";
import React, { useState} from "react";
import { BackupTable, Refresh } from "#mui/icons-material";
import useStyles from "./styles";
//Tabelle
import MUIDataTable, { ExpandButton } from "mui-datatables";
import { TableRow, TableCell } from "#mui/material";
import { createTheme, ThemeProvider } from "#mui/material/styles";
import total from "./test.csv";
import lost1 from "./test.csv";
import lost2 from "./test.csv";
//const App = () => {
function App() {
const { classes } = useStyles();
const [file, setFile] = useState();
const [array, setArray] = useState([]);
const csvFileToArray = (string) => {
const csvHeader = string.slice(0, string.indexOf("\n")).split(",");
const csvRows = string.slice(string.indexOf("\n") + 1).split("\n");
const array = csvRows.map((i) => {
const values = i.split(",");
const obj = csvHeader.reduce((object, header, index) => {
object[header] = values[index];
return object;
}, {});
return obj;
});
setArray(array);
setCols(initFilter(Object.keys(Object.assign({}, ...array))));
};
const headerKeys = Object.keys(Object.assign({}, ...array));
let [selectedFilter, setSelectedFilter] = useState([new Array()]);
let [cols, setCols] = useState();
//Tabelle
const components = {
ExpandButton: function (props) {
return <ExpandButton {...props} />;
},
};
var removedFilterList=[];
const options = {
filter: true,
filterType: "multiselect",
onFilterChange: (changedColumn, filterList) => {
cols = modifyFilter(cols, filterList);
},
onFilterChipClose: (index, removedFilter, filterList) => {
removedFilterList = filterList;
selectedFilter = filterList;
},
responsive: "standard",
selectableRowsOnClick: false,
rowHover: true,
expandableRows: false,
expandableRowsHeader: false,
expandableRowsOnClick: true,
selectableRows: "none",
rowsPerPage: 100,
filterList: [],
selectableRowsHideCheckboxes: false,
onCellClick: (rowData, rowMeta) => {
onFilter(rowData, rowMeta);
},
};
const theme = createTheme({
overrides: {
MUIDataTableSelectCell: {
expandDisabled: {
// Soft hide the button.
visibility: "hidden",
},
},
MUIDataTableBodyCell: {
styleOverrides: {
root: {
backgroundColor: "#FF0000",
},
},
},
},
});
const initFilter = (cols) => {
//add options to columns
for (let i = 0; i < cols.length; i++) {
cols[i] = {
name: cols[i],
options: {
filterList: []
}
}
}
return cols;
}
let modifyFilter = (colss, newFilterArray) => {
for (let i = 0; i < colss.length; i++) {
colss[i].options.filterList = newFilterArray[i];
}
return colss;
}
const onFilter = (value, rowMeta) => {
let filteredCols = [...cols];
if (value !== "All") {
if (selectedFilter.length < rowMeta.colIndex + 1) {
for (let i = selectedFilter.length; i < rowMeta.colIndex + 1; i++) {
selectedFilter.push(new Array());
}
}
let schonVorhanden = selectedFilter[rowMeta.colIndex].indexOf(value);
if (schonVorhanden == "-1") {
selectedFilter[rowMeta.colIndex].push(value);
}
else {
console.log(value, "schon vorhanden");
}
}
filteredCols[rowMeta.colIndex].options.filterList = selectedFilter[rowMeta.colIndex];
setCols(filteredCols);
};
//---------------------------
//TEST
const ImportSamples = () => {
let input = total;
if(file == "lost1"){
input=lost1;
}
if (array.length == 0) {
fetch(input)
.then((r) => r.text())
.then((text) => {
csvFileToArray(text);
});
}
};
const doSetFile = (wert) => {
setFile(wert);
ImportSamples();
Refresh();
}
ImportSamples();
return (
<>
<CssBaseline />
<AppBar position="relative">
<Toolbar>
<BackupTable className={classes.icon} />
<Typography variant="h6">SampleProject Tabelle</Typography>
</Toolbar>
</AppBar>
<main>
<div className={classes.container}>
<Container maxWidth="sm">
<Typography
variant="h2"
align="center"
color="textPrimary"
gutterBottom
>
SampleProject
</Typography>
<Typography
variant="h5"
align="center"
color="textSecondary"
paragraph
>
Viewer
</Typography>
<div className={classes.button}>
<Grid container spacing={2} justifyContent="center">
<Grid item>
<Button variant="contained" color="primary" onClick={() => doSetFile('lost1')}>
Erste Aktion
</Button>
</Grid>
<Grid item>
<Button variant="outlined" color="primary">
Zweite Aktion
</Button>
</Grid>
</Grid>
</div>
</Container>
</div>
<div className={classes.container}>
<Container maxWidth="false">
<ThemeProvider theme={theme}>
<MUIDataTable
title={"SampleProject"}
data={array}
columns={cols}
components={components}
options={options}
/>
</ThemeProvider>
</Container>
</div>
</main>
<footer className={classes.footer}>
<Typography variant="h6" align="center" gutterBottom>
Footer
</Typography>
<Typography variant="subtitle1" align="center" color="textSecondary">
Something here to give the footer a purpose!
</Typography>
</footer>
</>
);
}
export default App;

Function Query.where() requires a valid third argument, but it was undefined when trying to view the page

I'm trying to implement rating system in my shopping app, but received error console when trying to open the page.
The error on console are:
Function Query.where() requires a valid third argument, but it was undefined. - it points to:
this.stars = this.starService.getProductStars(this.movieId)
AND
const starsRef = this.afs.collection('stars', ref => ref.where('movieId', '==', movieId));
Below is my code:
rating.page.html: (where I put my 2 of components which are TestRate and Star-Review)
<ion-content>
<app-testrate></app-testrate>
<app-star-review-component></app-star-review-component>
</ion-content>
testrate.component.html:
<div *ngIf="movie | async as m">
<h1>
{{m.title}}
</h1>
<img [src]="m.image" width="100px">
<p>
{{m.plot}}
</p>
<star-review [movieId]="movieId" [userId]="userId"></star-review>
</div>
testrate.component.ts:
export class TestrateComponent implements OnInit {
userDoc: AngularFirestoreDocument<any>;
movieDoc: AngularFirestoreDocument<any>;
user: Observable<any>;
movie: Observable<any>;
constructor(private afs: AngularFirestore) { }
ngOnInit() {
this.userDoc = this.afs.doc('users/test-user-3')
this.movieDoc = this.afs.doc('movies/battlefield-earth')
this.movie = this.movieDoc.valueChanges()
this.user = this.userDoc.valueChanges()
}
get movieId() {
return this.movieDoc.ref.id
}
get userId() {
return this.userDoc.ref.id
}
}
star-review.component.html:
<h3>Average Rating</h3>
{{ avgRating | async }}
<h3>Reviews</h3>
<div *ngFor="let star of stars | async">
{{ star.userId }} gave {{ star.movieId }} {{ star.value }} stars
</div>
<h3>Post your Review</h3>
<fieldset class="rating">
<ng-container *ngFor="let num of [5, 4, 3, 2, 1]">
full star
<input (click)="starHandler(num)"
[id]="'star'+num"
[value]="num-0.5"
name="rating"
type="radio" />
<label class="full" [for]="'star'+num"></label>
half star
<input (click)="starHandler(num-0.5)"
[value]="num-0.5"
[id]="'halfstar'+num"
name="rating"
type="radio" />
<label class="half" [for]="'halfstar'+num"></label>
</ng-container>
</fieldset>
star-review.component.ts:
export class StarReviewComponentComponent implements OnInit {
#Input() userId;
#Input() movieId;
stars: Observable<any>;
avgRating: Observable<any>;
constructor(private starService: StarService) { }
ngOnInit() {
this.stars = this.starService.getProductStars(this.movieId)
this.avgRating = this.stars.pipe(map(arr => {
const ratings = arr.map(v => v.value)
return ratings.length ? ratings.reduce((total, val) => total + val) / arr.length : 'not reviewed'
}))
}
starHandler(value) {
this.starService.setStar(this.userId, this.movieId, value)
}
}
star.service.ts:
export class StarService {
constructor(private afs: AngularFirestore) { }
// Star reviews that belong to a user
getUserStars(userId) {
const starsRef = this.afs.collection('stars', ref => ref.where('userId', '==', userId));
return starsRef.valueChanges();
}
// Get all stars that belog to a Product
getProductStars(movieId) {
const starsRef = this.afs.collection('stars', ref => ref.where('movieId', '==', movieId));
return starsRef.valueChanges();
}
// Create or update star
setStar(userId, movieId, value) {
// Star document data
const star: Star = { userId, movieId, value };
// Custom doc ID for relationship
const starPath = `stars/${star.userId}_${star.movieId}`;
// Set the data, return the promise
return this.afs.doc(starPath).set(star)
}
}

sending Angular 6 form including checkbox values not working with template driven forms

I'm trying to pass form values including checkboxes in angular 6 forms using formbuilder but I'm unable to read the value from checkbox. I am getting all the values from all the other input fields but only checkbox is not responding Here is my code:
<form [formGroup]="myGroup" (submit)="submit(myGroup.value)">
<div class="row">
<div class="col-sm-4" *ngFor="let info of myGroup.controls['myInfo'].controls; let i = index">
<label for="{{labelValue[i].name}}"> {{labelValue[i].label}}
<input type="{{labelValue[i].type}}" class="{{labelValue[i].class}}" [formControl]="info">
</label>
</div>
</div>
<div class="row">
<button class="form-control btn-sub" type=”submit”>
Submit Details
</button>
</div>
My component class:
import { ProposalService, CustomerDetails, ProposalNumber } from 'src/app/Services/Proposal-service/proposal.service';
export interface InputType{
name:string;
type: string;
label: string;
class:string;
}
export class ProposalComponent implements OnInit {
public labelValue: InputType[] = [
{name:"fname",type:"text",label:"First Name", class:"form-control"},
{name:"form60",type:"checkbox",label:"Is Collection Of form 60", class:"form-control"},
{name:"eia-num",type:"number",label:"EIA Number", class:"form-control"}
];
title = "Customer Details";
details: Observable<CustomerDetails>;
pNumber: ProposalNumber ;
public information: CustomerDetails[] = [
{name:"First Name", value:""},//
{name:"IsCollectionOfform60", value:true},
{name:"EIA Number", value:""}
];
myGroup : FormGroup;
constructor(private formBuilder: FormBuilder,
private _proposalService: ProposalService) { }
ngOnInit() {
this.myGroup = this.formBuilder.group({
myInfo: this.constructFormArray()
});
this.pNumber = <ProposalNumber>{proposalNumber: 0 ,message:"", status: ""};
}
constructFormArray()
{
const arr = this.information.map(cat => {
return this.formBuilder.control(cat.value);
});
return this.formBuilder.array(arr);
}
submit(form){
//this.loading = true;
console.log(form);
let mySelectedAddon = form.myInfo.map((currentValue,i)=> {
return { "name" : this.information[i].name , "value" : currentValue}
}
);
console.log(mySelectedAddon);
this._proposalService.loadCustomer(mySelectedAddon).subscribe((res: ProposalNumber) =>{
//this.loading = false;
console.log(res);
this.pNumber.proposalNumber = res.proposalNumber;
this.pNumber.message = res.message;
console.log(this.pNumber.proposalNumber);
return this.myGroup.value;
});
}
}
You need to use the 'change' event and pass the respective input value and event to a method onChange where you check if it's checked, then add the respective value to the formarray, if it's unchecked, remove the chosen email from the form array.
You can refer the below link:
https://stackblitz.com/edit/angular-rskaug?file=src%2Fapp%2Fapp.component.ts
Above example is useful to get the values of checkbox dynamically.

how to preview image before upload in ionic 3?

i am trying to upload and preview image using jquery. But getting this
Error
Property 'result' does not exist on type 'EventTarget'.
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
page.ts
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$('#file').on('change', function () {
readURL(this);
});
page.html
<label for="file" class="lbl"><i class="fa fa-plus-circle"></i> Add Attachment</label>
<input type="file" id="file" style="visibility: hidden">
<img src="#" id="blah">
what will be the solution?? i think this code is correct but just the problem is 'result' property. Thanks in advance
Some time ago, I used the following code to preview an image in Ionic.
In HTML:
<input type="file" value="" (change)="fileChange($event)">
<img *ngIf="img1" [src]="img1"/>
In JavaScript:
fileChange(event) {
if (event.target.files && event.target.files[0]) {
let reader = new FileReader();
reader.onload = (event:any) => {
this.img1 = event.target.result;
}
reader.readAsDataURL(event.target.files[0]); // to trigger onload
}
let fileList: FileList = event.target.files;
let file: File = fileList[0];
console.log(file);
}
Improvements are welcome
for ionic 4
In html
<img class="logo" src="{{img_new}}" *ngIf="img_new!=''"/>
<input type="file" name="image" accept="image/*" (change)="changeListener($event)">
In ts
changeListener($event): void {
this.file = $event.target.files[0];
console.log(this.file);
let reader = new FileReader();
reader.onload = ($event:any) => {
this.img_new = $event.target.result;
}
reader.readAsDataURL($event.target.files[0]);
}

Error loading MacroEngine script (file: LawyerProfileView.cshtml)

Working on site i been handed and suddnely a couple of macros have started playing up. Macro was working fine now suddenly this error showed up can anyone help here is the code.
#using umbraco.MacroEngines
#inherits umbraco.MacroEngines.DynamicNodeContext
#functions{
public void SetPageTitle(string title)
{
var page = HttpContext.Current.Handler as Page;
if (page != null){
page.Title = title;
}
}
public DynamicNode Homepage
{
get {
var homepage = Model;
while(homepage.NodeTypeAlias != "Homepage"){
homepage = homepage.Parent;
}
return homepage;
}
}
public HtmlString GetSocialMediaLink(string network, string url, string name)
{
var socialMediaRepo = Library.NodeById(-1).DescendantsOrSelf("SocialMediaNetworkRepository").First();
var socialNetworks = new List<DynamicNode>();
if (socialMediaRepo != null)
{
foreach (var child in socialMediaRepo.Children)
{
if(child.NodeTypeAlias.ToLower().Equals(network.ToLower())){
var icon = child.HasValue("CssClass") ? String.Format("<i class=\"{0}\"></i>", child.CssClass) : String.Format("<img src=\"/imagegen.ashx?altimage=/images/assets/clear.gif&image={0}\" alt=\"{1}\"/>", child.Icon, child.Name);
return new HtmlString(String.Format("<a target=\"_blank\" rel=\"no-follow\" href=\"{0}\" title=\"{3} on {1}\">{2}</a>", url, child.Name, icon, name) );
}
socialNetworks.Add(child);
}
}
return new HtmlString("");
}
}
#{
if (String.IsNullOrEmpty(Request["name"])){
return;
}
var profileId = Request["name"].Replace("-", " ").Replace("/", "");
var lawyersRepository = Library.NodeById(1316);
var isIntranet = Homepage.Name.IndexOf("intranet", StringComparison.OrdinalIgnoreCase) > -1;
var nodes = isIntranet ? lawyersRepository.Children.Where("Name.ToLower() = \"" + profileId.ToLower() + "\"") : lawyersRepository.Children.Where("!ProfileIsPrivate && Name.ToLower() = \"" + profileId.ToLower() + "\"");
if(!nodes.Any()){
return;
}
var node = nodes.First();
if (node == null || node.NodeTypeAlias != "LawyerRepositoryItem"){
return;
}
if (node.ProfileIsPrivate && !isIntranet){
return;
}
PageData["PageTitle"] = Model.Name + " - " + node.Name;
SetPageTitle(Model.Name + " - " + node.Name);
var hasContactInfo = (!String.IsNullOrEmpty(node.TelephoneNumber) || !String.IsNullOrEmpty(node.EmailAddress) || !String.IsNullOrEmpty(node.OfficeLocation));
<div class="profile">
<div class="row">
<div class="span4 profile-content">
<h1>#node.Name</h1>
<h3>#node.JobTitle</h3>
#Html.Raw(node.Biography.ToString())
</div>
<div class="span2">
<div class="profile-picture">
#{
if (!node.HasValue("ProfilePictureSquare")){
<img src="/imagegen.ashx?altimage=/images/assets/clear.gif&image=#Library.MediaById(node.ProfilePicture).umbracoFile" alt="#node.Name" />
}
else{
<img src="/imagegen.ashx?altimage=/images/assets/clear.gif&image=#Library.MediaById(node.ProfilePictureSquare).umbracoFile" alt="#node.Name" />
}
}
</div>
<div class="profile-quote">
<!--Tesimonial-->
#RenderPage("~/macroScripts/Widgets/Widget_RandomTestimonial.cshtml", #node.Id.ToString())
</div>
</div>
#if (hasContactInfo)
{
<div class="contact-information">
<div class="pull-left contact-details">
<h4>#Dictionary.ContactInformationHeading</h4>
<dl class="">
#{
if (node.HasValue("TelephoneNumber"))
{
<dd><strong>#Dictionary.Label_TelephoneShort:</strong> #node.TelephoneNumber</dd>
}
if (node.HasValue("EmailAddress"))
{
<dd><strong>#Dictionary.Label_EmailShort:</strong> #node.EmailAddress</dd>
}
if (node.HasValue("OfficeLocation"))
{
var officeNode = Library.NodeById(node.OfficeLocation);
<dd><strong>#Dictionary.Label_Office:</strong> #officeNode.Name</dd>
}
}
</dl>
</div>
<div class="pull-left contact-vcard">
<h4>
<i class="t-icon-vcard"></i> <span>#Dictionary.DownloadVCard</span></h4>
</div>
</div>
}
#{
var hasSocialMediaUrls = node.HasValue("FacebookUrl") || node.HasValue("TwitterUrl") || node.HasValue("LinkedInUrl") || node.HasValue("YouTubeUrl") || node.HasValue("BlogUrl");
if (hasSocialMediaUrls)
{
<div class="profile-social-links social-links">
<ul class="unstyled">
<li><strong>#Dictionary.Connect</strong></li>
#if (node.HasValue("FacebookUrl"))
{
<li>#GetSocialMediaLink("facebook", node.FacebookUrl, node.Name)</li>
}
#if (node.HasValue("TwitterUrl"))
{
<li>#GetSocialMediaLink("twitter", node.TwitterUrl, node.Name)</li>
}
#if (node.HasValue("LinkedInUrl"))
{
<li>#GetSocialMediaLink("linkedin", node.LinkedInUrl, node.Name)</li>
}
#if (node.HasValue("YouTubeUrl"))
{
<li>#GetSocialMediaLink("youtube", node.YouTubeUrl, node.Name)</li>
}
#if (node.HasValue("BlogUrl"))
{
<li>#GetSocialMediaLink("blogger", node.BlogUrl, node.Name)</li>
}
</ul>
</div>
}
}
</div>
<div class="gold-bar">
#Dictionary.SubmitTestimonialText
</div>
</div>
}
i have tried loading from a backup file but the problem persists.
You will need to find out why you got this error.
If you are running in a macro AND you are in WebForms mode, you can add ?umbDebugShowTrace=true (or ?umbDebug=true) at the url. (first check if the umbracoDebugMode appsetting in the web.config is true).
If this is not working, check the App_Data/Logs/ folder for any log files. You should see the complete error there. If you have an older version, check also the umbracoLog database table.
Best thing to do is to look in /App_Data/Logs/UmbracoTraceLog.txt which will show you the logs recorded for today.
This will reveal the root of the error and full stack trace.