Update view on orientation change - angular2-nativescript

I have registered a orientationChangedEvent like this:
app.on(app.orientationChangedEvent, (args: OrientationChangedEventData) => {
if (this.currentScreenWidth === screen.mainScreen.widthDIPs) {
this.currentScreenWidth = screen.mainScreen.heightDIPs;
} else {
this.currentScreenWidth = screen.mainScreen.widthDIPs;
}
this.configureGrid();
});
I have the following template:
<GridLayout [rows]="rows" [columns]="columns">
<ng-container *ngFor="let card of cards">
<StackLayout [row]="card.row" [col]="card.col" [colSpan]="card.colSpan">
<kirby-card>
<kirby-card-header [title]="'row: ' + card.row" [subtitle]="'col: ' + card.col">
</kirby-card-header>
<StackLayout class="content">
<Label text="Here you can add stuff, which is cool."></Label>
</StackLayout>
<kirby-card-footer>
<kirby-button label="Dummy Kirby Button" expand="block" shape="round" theme="cookbook"></kirby-button>
</kirby-card-footer>
</kirby-card>
</StackLayout>
</ng-container>
and in my configureGrid method I update the rows, columns and cards properties, but my view is not updating, the view (GridLayout) simply display exactly the same as before the rotation. I have logged out all the data, and my data does change, so it seems the data binding does not understand that the data has changed.
Can I somehow force a update of the view, or how do I fix this problem?
Thank you

Do the data update with NgZone, and all is good.

Related

how to show the selected value in radio button as checked when opening the ion-lost again after selection in ionic

I have a field which opens a list having ion-radio.On selection of an option it shows the selected value as checked and when i open the list again, the checked value is not shown.
here is my code:
code to show the options in modal controller :
let modal = this.modalCtrl.create(ListComponent, { selectEmpType: type, selectValue: value, customiseColor: this.customiseColor , formMrType :formMrType, limitedRoleList : this.limitedRoleList, formType:this.formType,defaultOU1:this.defaultOus[0],defaultOU2:this.defaultOus[1],defaultOU3:this.defaultOus[2]});
modal.onDidDismiss(data => {
if (data.type == 'single') {
this.setEmpValue(data.data, name); //data.data is the value that is selected from the list
}
}
in listcomponent.html:
<div *ngIf= "formMrType =='employee'">
<ion-list radio-group [(ngModel)]="relationship">
<ion-item *ngFor="let option of inputDatas">
<ion-label>{{option.EMPFullName}}</ion-label>
<ion-radio [checked]="option.checked" value="{{option.EMPFullName}}"></ion-radio>
</ion-item>
</ion-list>
</div>
how to show the selected option as checked when opening the list for second time.
Preferably, you should be using ion-select for such functionality..
If you are using latest ionic versions ion-radio-group
But even in your case..you can try something like this...
<ion-radio [checked]="option.checked" value="{{option.EMPFullName}}" (ionBlur)="optionBlur(option)"></ion-radio>
optionBlur(option){
if(!option['checked']){
option['checked'] = true;
}
else{
option['checked'] = !option['checked']
}
}

How to show button on selection of a value from the angular material select dropdown

Once i select a dropdown value from a dropdown field i want a section in another div to be loaded
ngif would help me do this, but how could i add this as a condition for the display of that section
Any dropdown selected should open that section
Later would customise it to different other sections in a div to load based on selection of the different dropdowns values accordingly
This can be solve by using selectionchange event emmiter function, whenever you select a value from the dropdown you can call an eventemmiter function. See the code below:
Html Code:
<div>
<mat-select placeholder="Options"
(selectionChange)="onSelecetionChange($event.value)">
<mat-option value="individual ">Individual </mat-option>
<mat-option value="business">Business</mat-option>
</mat-select>
</div>
<div *ngIf="individual">
Individual Div
</div>
<div *ngIf="business">
Business Div
</div>
My ts code:
individual: boolean;
business: boolean;
onSelecetionChange( value: string ) {
if( value === 'individual') {
// You can add some service call or customize your data from here
this.individual = true;
}
if( value === 'business') {
// You can add some service call or customize your data from here
this.business = true;
}
}

What is the best way to post form with multiple components using Vue js

as I'm on my Vue spree (started recently but so far I'm really enjoying learning this framework) couple of questions rised up. One of which is how to post form from multiple components. So before I continue forward I wanted to ask you what are you thinking about this way of structuring and point me in right direction if I'm wrong.
Here it goes.
I'm working on a SPA project using ASP.NET CORE 2.1 and Vue JS Template (with webpack)(https://github.com/MarkPieszak/aspnetcore-Vue-starter) and my project is structured in several containers, something like this:
In my app-root i registered several containers
<template>
<div id="app" class="container">
<app-first-container></app-first-container>
<app-second-container></app-second-container>
<!--<app-third-container></app-third-container>-->
<app-calculate-container></app-calculate-container>
<app-result-container></app-result-container>
</div>
</template>
<script>
// imported templates
import firstContainer from './first-container'
import secondContainer from './second-container'
import calculateContainer from './calculateButton-container'
//import thirdContainer from './third-container'
import resultContainer from './result-container'
export default {
components: {
'app-first-container': firstContainer,
'app-second-container': secondContainer,
// 'app-third-container': thirdContainer,
'app-calculate-container': calculateContainer,
'app-result-container': resultContainer
}
}
</script>
In my first container I'm having several dropdowns and two input fields with my script file where I'm fetching data from API and filling dropdowns and input fields with fetched data.
Something like this ( entered some dummy code for demonstration)
<template>
<div>
<h1>Crops table</h1>
<p>This component demonstrates fetching data from the server. {{dataMessage}}</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="exampleFormControlSelect1" class="col-form-label-sm font-weight-bold">1. Some text</label>
<select class="form-control" id="exampleFormControlSelect1" v-model="pickedCropType" #change="getCropsByType()">
<option v-for="(cropType, index) in cropTypes" :key="index" :value="cropType.id" :data-imagesrc="cropType.imgPath">{{ cropType.name }}</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="exampleFormControlSelect2" class="col-form-label-sm font-weight-bold">2. Some text</label>
<select class="form-control" id="exampleFormControlSelect2">
<option v-for="(crop, index) in cropSelectList" :key="index" :value="crop.id">{{ crop.name }}</option>
</select>
</div>
</div>
</div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
export default {
data() {
return {
cropTypes: null,
cropSelectList: null,
crops: null,
pickedCropType: null,
}
},
methods: {
loadPage: async function () {
try {
//Get crop types and create a new array with crop types with an added imgPath property
var cropTypesFinal = [];
let responseCropTypes = await this.$http.get(`http://localhost:8006/api/someData`);
responseCropTypes.data.data.forEach(function (element) {
cropTypesFinal.push(tmpType);
});
} catch (err) {
window.alert(err)
console.log(err)
}
},
getCropsByType: async function () {
//Get crops by crop type
let responseCrops = await this.$http.get(`http://localhost:8006/api/crop/Type/${this.pickedCropType}`);
var responseCropsData = responseCrops.data.data;
this.cropSelectList = responseCropsData;
}
},
async created() {
this.loadPage()
}
}
</script>
And in my second container I have different dropdowns and different input fields with different scripts etc.
So, my questions are:
1.) I'm having required data form field in first container and in second container I'm having additional data and my submit button is separated in third container (app-result-container). So, is this proper and logical way of structuring containers if not can you point me in right direction?
2.) Is it smart to input script tag in every container where I'm processing/fetching/submitting some data for that particular container? Should I put scripts tag in separated file and keep structure clean, separating html from js file.
Example:
import { something } from 'something'
export default {
data () {
return {
someData: 'Hello'
}
},
methods: {
consoleLogData: function (event) {
Console.log(this.someData)
}
}
}
3.) Can I send input values from one container to another (In my particular case from first and second container to app-calculate-container(third container))?
How to on submit return results container with calculated imported values
If you want components to communicate or share data with one another, you will need to either emit an event from one component up to the parent and pass it down via props, or use some kind of state management model, like Vuex, where each of your components can listen to the store.
Take a look at this code sandbox: https://codesandbox.io/s/8144oy7xy2
App.vue
<template>
<div id="app">
<child-input #input="updateName" />
<child-output :value="name" />
</div>
</template>
<script>
import ChildInput from "#/components/ChildInput.vue";
import ChildOutput from "#/components/ChildOutput.vue";
export default {
name: "App",
components: {
ChildInput,
ChildOutput
},
data() {
return {
name: ""
};
},
methods: {
updateName(e) {
this.name = e.target.value;
}
}
};
</script>
ChildInput.vue
<template>
<input type="text" #input="changeHandler">
</template>
<script>
export default {
name: "ChildInput",
methods: {
changeHandler(e) {
this.$emit("input", e);
}
}
};
</script>
ChildOutput.vue
<template>
<p>{{ value }}</p>
</template>
<script>
export default {
name: "ChildOutput",
props: {
value: {
type: String,
default: ""
}
}
};
</script>
What's going on?
The ChildInput component is a text field and on every change inside it, fires an event (emits using this.$emit() and passes the whole event up).
When this fires, App is listening to the change, which fires a method that updates the name data property.
Because name is a reactive data property and is being passed down as a prop to the ChildOutput component, the screen re-renders and is updated with the text written.
Neither ChildInput nor ChildOutput knows about one another. It's the parent that listens to the event passed to it, then passes the new prop down.
This way of working is fine and simple to understand, but I would strongly recommend looking at Vuex, as this method can get messy and complicated when you go beyond trivial tasks.

Ionic Master Detail view with Firebase auto-generated child key returning JSON $value null

I am new to Ionic and Firebase. While fetching data for details view I am getting undefined value for $scope.program.
However, I have fetched the complete programs list in Master view. Clicking the list item from master view returns index (0, 1, 2, etc) of the list in console log but not the child key (which I was expecting)
During my research, I found out this question quite relevant to my problem, by Wes Haq. But while implementing the same, it has no change in the result. Please help.
From the above question by Wes Haq, I couldn't find the state provider details. I may be missing something there. Thanks in advance to all.
controllers.js
.controller('myServicesCtrl', ['$scope', '$state', '$stateParams', '$ionicActionSheet', 'AgencyProgService',
function ($scope, $state, $stateParams, $ionicActionSheet, AgencyProgService) {
//Only items relative to the logged/signed in Agency shall be pushed to the scope.items
$scope.programs = AgencyProgService.getPrograms();
}])
.controller('serviceDetailCtrl', ['$scope', '$stateParams', 'AgencyProgService',
function ($scope, $stateParams, AgencyProgService) {
AgencyProgService.getProgram($stateParams.index).then(function (program) {
$scope.program = program;
});
console.log("serviceDetailCtrl: scope.program is: " + $scope.program);
}])
service.js
.service('AgencyProgService', ['$q', '$firebaseArray', '$firebaseObject', 'AgencyDataService', function ($q, $firebaseArray, $firebaseObject, AgencyDataService) {
var ref = firebase.database().ref().child('programs/'); // this is a valid ref with https://my-demo.firebaseio.com/programs
var agencyIDfromPrograms = AgencyDataService.getAgencyUID();
var refFilter = ref.orderByChild("agencyID").equalTo(agencyIDfromPrograms);
return {
getPrograms: function () {
return $firebaseArray(refFilter);
},
getProgram: function (programId) {
console.log("getProgram: ID is: " + programId + "And refFilter to use is: " + ref);
var deferred = $q.defer();
var programRef = ref.child(programId); // here programId should be the autogenerated child key from fire DB "programs"
var program = $firebaseObject(programRef);
deferred.resolve(program);
return deferred.promise;
}
}
}])
Views:
myServices.html
<ion-list id="myServices-list9">
<ion-item id="myServices-list-item11"
ng-repeat="item in programs" ui- sref="serviceDetail({index: $index})">
<div class="item-thumbnail-left">
<i class="icon"></i>
<h2>{{item.progName}} </h2>
<p>{{item.servType}} for: {{item.servHours}}</p>
<p>From: {{item.servStartDate}}</p>
</div>
</ion-item>
</ion-list>
serviceDetail.html
<div class="list card">
<div class="item item-avatar">
<img src="{{item.user.picture.thumbnail}} " />
<h1>{{program.servContact}}</h1>
<h2>{{program.$id}} {{program.progName}}</h2>
<p>{{item.servContact}} {{item.servStartDate}}</p>
</div>
<pre> {{program | json}} </pre>
From serviceDetail view, no data from program is visible, as you can see from the screen shot below. List card for serviceDetail. on clicking 2nd item on myServices, it shows this detail screen with $id as 1. Expected is the child key for programs:
Firebase data structure screenshot for child programs is as below,
Appreciate your suggestions.

ReactJs: Wrap Semantic UI Modal using Portal "pattern"

I'm trying to wrap Semantic UI Modal component using portal approach described here
Here is my take at it http://jsfiddle.net/mike_123/2wvfjpy9/
I'm running into issue though, when obtaining a DOM reference and Rendering new markup into it there seem to be old reference still maintained.
render: function() {
return <div className="ui modal"/>; <-- the idea at first was to only return <div/>
},
...
React.render(<div > <----------- originally this element had className="ui modal", but this.node doesn't seem to overtake the original node reference
<i className="close icon"></i>
<div className="header">test</div>
<div className="content">
{props.children}
</div>
</div>, <-----------
this.node);
Any pointers how fix this test case http://jsfiddle.net/mike_123/2wvfjpy9/
You will lose correct vertical positioning and probably animations with approaches mentioned above.
Instead, you can just place your modal's component inside your app's root component and call .modal() with detachable: false. With this option, semantic wouldn't make any DOM manipulations and you won't lose your React DOM event listeners.
Example using Webpack/Babel:
import React, { Component } from 'react'
import $ from 'jquery'
if (typeof window !== 'undefined') {
window.jQuery = $
require('semantic-ui/dist/semantic.js')
}
class App extends Component {
state = {
showModal: false
}
_toggleModal = (e) => {
e.preventDefault()
this.toggleModalState()
}
toggleModalState = () => {
this.setState({ showModal: !this.state.showModal })
}
render() {
return (
<div>
<a href="" onClick={this._toggleModal}></a>
{this.state.showModal
? <Modal toggleModalState={this.toggleModalState}/>
: ''}
</div>
)
}
}
class Modal extends Component {
componentDidMount() {
$(this.modal)
.modal({ detachable: false })
.modal('show')
}
componentWillUnmount() {
$(this.modal).modal('hide')
}
_close = (e) {
e.preventDefault()
alert("Clicked")
this.props.toggleModalState()
}
render() {
return (
<div ref={(n) => this.modal = n} className="ui modal">
<div class="content">
<a onClick={this._close} href="">Click Me</a>
</div>
</div>
)
}
}
When you call this.$modal.modal('show'), it will actually restructure your DOM, and React will not be happy about it. Plus, if you try to put control in your modal, the control will not work.
What you should do is to React.render an already shown modal, i.e. a modal with markup as if $('.ui.modal').modal('show') has been called.
Here is my attempt using "React-Portal" to help with rendering a react component at body level. You can still use your method if you prefer.
// modal.jsx
import React, { Component } from 'react';
import Portal from 'react-portal';
class InnerModal extends Component {
constructor(props) {
super(props);
this.state = { modalHeight: 0 };
}
componentDidMount() {
let modalHeight = window.$('#reactInnerModal').outerHeight();
this.setState({modalHeight: modalHeight});
}
render() {
return (
<div id='reactInnerModal' className='ui standard test modal transition visible active' style={{'margin-top': - this.state.modalHeight / 2}}>
<i className='close icon' onClick={this.props.closePortal}></i>
{this.props.children}
</div>
);
}
}
class Modal extends Component {
render() {
let triggerButton = <button className='ui button'>Open Modal</button>;
return (
<Portal className='ui dimmer modals visible active page transition' openByClickOn={triggerButton} closeOnEsc={true} closeOnOutsideClick={true}>
<InnerModal>
{this.props.children}
</InnerModal>
</Portal>
);
}
}
export default Modal;
Notice that my modal has already been rendered in the markup.
You can then consume the modal as below:
// index.jsx
import React, { Component } from 'react';
import Modal from './modal';
class ModalDemo extends Component {
render() {
return (
<Modal>
<div className='header'>
Profile Picture
</div>
<div className='image content'>
<div className='ui medium image'>
<img src='http://semantic-ui.com/images/avatar2/large/rachel.png' />
</div>
<div className='description'>
<div className="ui header">We've auto-chosen a profile image for you.</div>
<p>We've grabbed the following image from the <a href='https://www.gravatar.com' target='_blank'>gravatar</a> image associated with your registered e-mail address.</p>
<p>Is it okay to use this photo?</p>
</div>
</div>
<div className='actions'>
<div className='ui black deny button'>
Nope
</div>
<div className='ui positive right labeled icon button'>
Yep, that's me
<i className='checkmark icon'></i>
</div>
</div>
</Modal>
);
}
}
React.render(<ModalDemo />, document.getElementById('content'));
With this you don't have to hack your way into DOM manipulation with jQuery, and the control in the modal (button, link, etc, to invoke functions) still works.
Hope this help!
Khanetor answered this question thoroughly and correctly, I just want to contribute one additional tidbit about how to position the Modal. It would be best as a comment, but unfortunately, I don't have the reputation to do so.
Anyways, the first child element of the Portal element needs to be positioned absolutely in order to make the dimmer and resulting modal sit on top of the page content rather than get put beneath it.
First, add style={position:'absolute'} to the Portal declaration in Modal's render method so the dimmer gets set at the top of the page. You end up with:
<Portal className='ui dimmer modals visible active page transition' openByClickOn={triggerButton} closeOnEsc={true} closeOnOutsideClick={true} style={position:'absolute'}>
<InnerModal>
{this.props.children}
</InnerModal>
</Portal>
Next, set the InnerModal's position to relative and decide on a distance from the top of the screen. I used an eighth (or 0.125) of the browser's viewport and got:
class InnerModal extends Component {
constructor(props){
super(props);
this.state = {
modalId : _.uniqueId('modal_'),
style: {}
}
}
componentDidMount() {
this.setState({
style : {
position : 'relative',
top : $(window).height() * 0.125 + 'px'
}
});
}
render(){
return (
<div id={this.state.modalId} className='ui standard modal transition visible active'
style={this.state.style}>
<i className='close icon' onClick={this.props.closePortal}></i>
{ this.props.children }
</div>
);
}
}
With those edits made, I've finally got some working modals in React! Hope this is helpful to someone else running into some of the same issues I've been.