How to Configure Dynamic Environment in angular

I usually do “.environment.ts” files to set environments. When i build the code I do 3 builds those are dev, test and production. Single build is not possible for all environments i did two approaches to set environments. I will explain both here.

Method 1:

If you know your Test, Dev and production URLs before build you use this method. This is Static one. First Create a project using below command.

ng new dynamic-envs

Go to newly created project and Create a static service using below command

ng g s services/env1

Then Identify the current url and set your environment according to that.

import { Injectable } from '@angular/core';
import {PlatformLocation } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class Env1Service {

  constructor(public platformLocation: PlatformLocation) { }

  getEnv() {
    /**  Identify current url */
    const currentURL = (this.platformLocation as any).location.origin;
    /** set envronment default dev */
    let envs = {apiURL: 'http://dev.com', mode: 'dev'};

    /** I assumed my current url is related to test I set my Test envronments. Do for production also same */
    if (currentURL === 'http://localhost:4001') {
      envs.apiURL = 'http://test.com',
      envs.mode = 'Test';
    } else if (currentURL === 'http://localhost:4002') {
      envs.apiURL = 'http://prod.com',
      envs.mode = 'Production';
    }
    return envs;
  }
}

Inject this service what ever you want and use “getEnv()” function for identify the environment.

export class AppComponent implements OnInit {
  title = 'dynamic-envs';
  apiURL1: string;
  mode1: string;
  constructor(private env1: Env1Service) { }

  ngOnInit() {
    /* First Method */
    const getData = this.env1.getEnv();
    this.apiURL1 = getData.apiURL;
    this.mode1 = getData.mode;
  }
}

Method 2:

This is little bit complex but dynamic one. First you Create “envronments.json” file in assets file.

{
“apiURL”: “http://dev.com”,
“mode”: “Development”
}

Create a service using below command

ng g s services/env2

Load Environment Variables from Json File

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {shareReplay} from 'rxjs/operators';

interface Envronment {
  apiURL: string;
  mode: string;
}

@Injectable({
  providedIn: 'root'
})
export class Env2Service {

  private readonly ENV_URL = 'assets/envronments.json';
  public Envronment$: Observable<Envronment>;

  constructor(private http: HttpClient) {
  }

  public loadEnvronments(): any {
    if (!this.Envronment$) {
      this.Envronment$ = this.http.get<Envronment>(this.ENV_URL).pipe(
        shareReplay(1)
      );
    }
    return this.Envronment$;
  }

}

Initialize this service in app.module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { Env1Service } from './services/env1.service';
import { Env2Service } from './services/env2.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    Env1Service,
    {
      provide: APP_INITIALIZER,
      useFactory: (Env2Service: Env2Service) => () => Env2Service.loadEnvronments().toPromise(),
      deps: [Env2Service],
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Use this service like below.

import { Component, OnInit } from '@angular/core';
import { Env1Service } from './services/env1.service';
import { Env2Service } from './services/env2.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'dynamic-envs';
  apiURL1: string;
  mode1: string;
  apiURL2: string;
  mode2: string;
  constructor(private env1: Env1Service, private env2: Env2Service) { }

  ngOnInit() {
    /* First Method */
    const getData = this.env1.getEnv();
    this.apiURL1 = getData.apiURL;
    this.mode1 = getData.mode;

    /* second Method */
    this.env2.Envronment$.subscribe(res => {
      this.apiURL2 = res.apiURL;
      this.mode2 = res.mode;
    });
  }
}

After build you change your “envronments.json” file according to your environment.

Git Link: https://github.com/iamchandu/dynamic-envs-angular

How to convert HTML Template to React Js Template

In this Post I am explains about Basic HTML template to React Js Template conversion.

First you need to install sample React Js Project using below command.

npx create-react-app html-to-react-app

Take your HTML template (I downloaded My HTML template from https://templated.co/industrious).

Create two folders “src/assets” and “public/assets” in your react project.

Copy all your HTML template js files to “public/assets” folder.

Copy all your HTML template assets (Except js files) to “src/assets” folder.

Remove all the content in “App.css” and import all your css files in “App.css” using “@import” statement.

Import all your scripts to “public/index.html” file using script tag (http://abc.js)

In App.js Write below code.

return (
/* Your Template index.html code */
);

Remove all HTML comments.
Close all self closed tags properly.
change all “class” attributes to “className”

Thank you..

How to do custom format dates in React Js

First Create New React Project using below command

create-react-app date-format

cd date-format

Create functional component named as date-format.js

import React from ‘react’;
const Date = (props) =>{
// ============ Code Here ==========
}
export default Date;

Create Array with all months Data

const montsArr = [“”,”January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”];

Get all input objects and save to constants

const inputformat = props.input.split(‘-‘);
const outputformat = props.output.split(props.outputDelemeter);
const dateval = props.data.split(‘-‘);
const dateObj = {};

Construct date Object with all parameters using below loop

dateval.forEach((element, i) => {
dateObj[inputformat[i]] = element;
switch(inputformat[i]) {
case ‘M’:
dateObj.m = montsArr.findIndex(v=> v === element);
break;
case ‘m’:
dateObj.M = montsArr[Number(element)];
break;
case ‘y’:
dateObj.Y = ’20’+element;
break;
case ‘Y’:
dateObj.y = element.substring(0,2);
break;
case ‘d’:
let daysurfex = ‘th’;
if(Number(element) === 1 || Number(element) === 21){
daysurfex = ‘st’;
} else if(Number(element) === 2 || Number(element) === 22) {
daysurfex = ‘nd’;
} else if(Number(element) === 3) {
daysurfex = ‘rd’;
}
dateObj.D = element+daysurfex;

}
});

Finally construct Output String

let finalDate = ”;
outputformat.forEach((v,i) => {
if(finalDate){
finalDate+=props.outputDelemeter;
}
finalDate+=dateObj[v];
})

Return this final output string

return (

<h5>{finalDate}</h5>
)

Full Code of date-format.js

import React from ‘react’;

const Date = (props) =>{
const montsArr = [“”,”January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”];
const inputformat = props.input.split(‘-‘);
const outputformat = props.output.split(props.outputDelemeter);
const dateval = props.data.split(‘-‘);
const dateObj = {};
dateval.forEach((element, i) => {
dateObj[inputformat[i]] = element;
switch(inputformat[i]) {
case ‘M’:
dateObj.m = montsArr.findIndex(v=> v === element);
break;
case ‘m’:
dateObj.M = montsArr[Number(element)];
break;
case ‘y’:
dateObj.Y = ’20’+element;
break;
case ‘Y’:
dateObj.y = element.substring(0,2);
break;
case ‘d’:
let daysurfex = ‘th’;
if(Number(element) === 1 || Number(element) === 21){
daysurfex = ‘st’;
} else if(Number(element) === 2 || Number(element) === 22) {
daysurfex = ‘nd’;
} else if(Number(element) === 3) {
daysurfex = ‘rd’;
}
dateObj.D = element+daysurfex;

}
});
let finalDate = ”;
outputformat.forEach((v,i) => {
if(finalDate){
finalDate+=props.outputDelemeter;
}
finalDate+=dateObj[v];
})
return (

<h5>{finalDate}</h5>
)

}

export default Date;

Import this class what ever you want and set input and output parameters like below

import React from ‘react’;
import Dateformat from ‘./date-format’

function App() {
return (

className=”App”>
input=’Y-m-d’ output=’D M Y’ data=’2020-10-25′ outputDelemeter = ‘ ‘/>
input=’Y-m-d’ output=’d-m-Y’ data=’2020-10-01′ outputDelemeter = ‘-‘/>
input=’Y-m-d’ output=’d/m/y’ data=’2020-10-01′ outputDelemeter = ‘/’/>
input=’d-m-Y’ output=’M D Y’ data=’09-10-2020′ outputDelemeter = ‘ ‘/>
input=’M-d-Y’ output=’Y-m-d’ data=’October-09-2020′ outputDelemeter = ‘-‘/>


);
}

export default App;

OutPut:

Output screen

GitLink: https://github.com/iamchandu/How-to-do-custom-format-dates-in-React-Js

How to Create and Edit Canvas Using angular and fabric js

First Create New angular project

ng new canvas-edit

Install Fabric js using below command

npm install fabric –save

In your component.ts file import fabric js

import { fabric } from ‘fabric’;

Declare the variables as below

private canvas: any;
 private textString: string;
 private size: any = {
   width: 1200,
   height: 1000
 };
 private OutputContent: string;

Then Initialize the values and objects in ngOnInit() function

this.canvas = new fabric.Canvas('canvas', {
  hoverCursor: 'pointer',
  selection: true,
  selectionBorderColor: 'blue'
});
this.textString = null;
this.canvas.setWidth(this.size.width);
this.canvas.setHeight(this.size.height);
this.OutputContent = null;

Add some text to Canvas using below function

addText() {
    let textString = this.textString;
    let text = new fabric.IText(textString, {
      left: 10,
      top: 10,
      fontFamily: 'helvetica',
      angle: 0,
      fill: '#000000',
      scaleX: 0.5,
      scaleY: 0.5,
      fontWeight: '',
      hasRotatingPoint: true
    });
    this.extend(text, this.randomId());
    this.canvas.add(text);
    this.selectItemAfterAdded(text);
    this.textString = '';
}

extend(obj, id) {
	obj.toObject = (function (toObject) {
	  return function () {
		return fabric.util.object.extend(toObject.call(this), {
		  id: id
		});
	  };
	})(obj.toObject);
}
//======= this is used to generate random id of every object ===========
randomId() {
	return Math.floor(Math.random() * 999999) + 1;
}
//== this function is used to active the object after creation ==========
selectItemAfterAdded(obj) {
	this.canvas.discardActiveObject().renderAll();
	this.canvas.setActiveObject(obj);
}

Then Create Shapes like Triangle, square, circle using below code

addFigure(figure) {
	let add: any;
	switch (figure) {
	  case 'rectangle':
		add = new fabric.Rect({
		  width: 200, height: 100, left: 10, top: 10, angle: 0,
		  fill: '#3f51b5'
		});
		break;
	  case 'square':
		add = new fabric.Rect({
		  width: 100, height: 100, left: 10, top: 10, angle: 0,
		  fill: '#4caf50'
		});
		break;
	  case 'triangle':
		add = new fabric.Triangle({
		  width: 100, height: 100, left: 10, top: 10, fill: '#2196f3'
		});
		break;
	  case 'circle':
		add = new fabric.Circle({
		  radius: 50, left: 10, top: 10, fill: '#ff5722'
		});
		break;
	}
	this.extend(add, this.randomId());
	this.canvas.add(add);
	this.selectItemAfterAdded(add);
}

Export your designed canvas to various formats(JSON, SVG)

  ExportToContent(input) {
    if(input == 'json'){
      this.OutputContent = JSON.stringify(this.canvas);
    }else if(input == 'svg'){
     this.OutputContent = this.canvas.toSVG();
    }
  }

Final HTML Code like Below.

<input type="text" [(ngModel)]="textString"/><button (click)="addText()">Add</button>
   
<button (click)="addFigure('triangle')">Triangle</button>
<button (click)="addFigure('circle')">Circle</button>
<button (click)="addFigure('square')">Square</button>
<button (click)="addFigure('rectangle')">Rectangle</button>

  

<button (click)="ExportToContent('json')">Generate Json</button>
<button (click)="ExportToContent('svg')">Generate SVG</button>
<br/>
<code>{{OutputContent}}</code>
<canvas id="canvas"></canvas>

<router-outlet></router-outlet>

Git Link: https://github.com/iamchandu/how-to-create-and-edit-canvas-using-angular-and-fabric-js

How to generate PDF using Nest JS

First Create Nest application

nest new generate-pdf
cd generate-pdf

Then install pdfmake NPM plugin

npm install pdfmake

In your controller Import below

import * as fs from ‘fs’;
import * as PdfPrinter from ‘pdfmake’;
import * as uuid from ‘uuid/v4’;

In your function add the below code

@Get('/generatePDF')
  generatePDF() {
    const fonts = {
      Helvetica: {
        normal: 'Helvetica',
        bold: 'Helvetica-Bold',
        italics: 'Helvetica-Oblique',
        bolditalics: 'Helvetica-BoldOblique'
      }
    };
    const printer = new PdfPrinter(fonts);

    const docDefinition = {
      content: [
        { text: 'Heading', fontSize: 25},
        {
          layout: 'lightHorizontalLines', // optional
          table: {
            headerRows: 1,
            widths: [ '*', 'auto', 100, '*' ],

            body: [
              [ 'First', 'Second', 'Third', 'The last one' ],
              [ 'Value 1', 'Value 2', 'Value 3', 'Value 4' ],
              [ 'Val 1','Val 2', 'Val 3', 'Val 4' ]
            ],
          },
        },
        {text: 'google', link: 'http://google.com', pageBreak: 'before',},
        { qr: 'text in QR', foreground: 'green', background: 'white' },
      ],
      defaultStyle: {
        font: 'Helvetica'
      }
    };

    const options = {
    }
    let file_name = 'PDF' + uuid() + '.pdf';
    const pdfDoc = printer.createPdfKitDocument(docDefinition, options);
    pdfDoc.pipe(fs.createWriteStream(file_name));
    pdfDoc.end();
    return {'file_name': file_name};
  }

Reference: http://pdfmake.org/#/

How to import CSV File in Angular

create new angular instance using below command

ng new csv-upload

Past the below code in your .html file

<input type=”file” #fileImportInput name=”File Upload” id=”txtFileUpload” (change)=”fileChangeListener($event)” accept=”.csv” />
<table>
<tr *ngFor=”let item of csvRecords”>
<td *ngFor=”let single of item”>{{single}}</td>
</tr>
</table>

add this line is in your .ts file

@ViewChild(‘fileImportInput’) fileImportInput: any;

Create a function for read the file

fileChangeListener($event: any): void {

//=============== write our code ======================

}

Check the given file is .csv or not

 var files = $event.srcElement.files;    

if (files[0].name.endsWith(‘.csv’)) {

//======== write your code ============

}else{
  alert(‘Please import valid .csv file.’);
  this.fileImportInput.nativeElement.value = ”;

}

Create an object for a reader and read the file

var input = $event.target;      

var reader = new FileReader();      

reader.readAsText(input.files[0]);
reader.onload = (data) => {

//====== we got string data we need to split that data into object====

}

Split the “,” separated data and push to our object

let csvData = reader.result;        

let csvRecordsArray = (csvData as string).split(/\r\n|\n/);

for(let i=0;i<csvRecordsArray.length;i++){

let rowdata = csvRecordsArray[i].match(/(“[^”]*”)|[^,]+/g);

this.csvRecords.push(rowdata);

}

Full .ts file code:


public csvRecords: any[] = [];
@ViewChild(‘fileImportInput’) fileImportInput: any;
  fileChangeListener($event: any): void {
    var files = $event.srcElement.files;
    if (files[0].name.endsWith(‘.csv’)) {
      var input = $event.target;
      var reader = new FileReader();
      reader.readAsText(input.files[0]);
      reader.onload = (data) => {
        let csvData = reader.result;
        let csvRecordsArray = (csvData as string).split(/\r\n|\n/);
for(let i=0;i<csvRecordsArray.length;i++){
let rowdata = csvRecordsArray[i].match(/(“[^”]*”)|[^,]+/g);
this.csvRecords.push(rowdata);
}
      };
reader.onerror = function() {
        alert(‘Unable to read ‘ + input.files[0]);
      };
    } else {
      alert(‘Please import valid .csv file.’);
      this.fileImportInput.nativeElement.value = ”;
     this.csvRecords = [];
    }
}

User Authentication in ReactNative using ReactNavigation

Install Reactnative Cli globally.

npm install -g react-native-cli

Create a project

react-native init ReactNativeBasicAuthentication

Install Pre requests like react navigation and react native elements

npm install –save react-navigation

npm install –save react-native-gesture-handler

npm i react-native-elements –save

npm i –save react-native-vector-icons

react-native link

Here User authentication details save in local storage of the mobile. so replace the below code in App.js

import { createSwitchNavigator, createStackNavigator, createAppContainer } from ‘react-navigation’;

import Login from ‘./app/components/Login’;

import AuthLoading from ‘./app/components/AuthLoading’;

import Home from ‘./app/components/Home’;

import Signup from ‘./app/components/Signup’;

import Products from ‘./app/components/main/Products’;

const AppStack = createStackNavigator({ Home: Home, Products: Products });

const AuthStack = createStackNavigator({ Login: Login, Signup: Signup });

export default createAppContainer(createSwitchNavigator( { AuthLoading: AuthLoading, App: AppStack, Auth: AuthStack, }, { initialRouteName: ‘AuthLoading’, }));

Then Create app/components folder


Login.js

import React, {Component} from ‘react’;
import { View, AsyncStorage, Alert} from ‘react-native’;
import { Card, Button, FormLabel, FormInput, Header, Divider } from ‘react-native-elements’;

export default class Login extends React.Component {
state = {
email: ”,
password: ”
};
static navigationOptions = {
header:null,
};

render() {
return (
<View>
<Header
centerComponent={{ text: ‘Login’, style: { color: ‘#fff’ } }}
outerContainerStyles = {{height:50}}
/>
<Card title=”Login”>
<FormLabel>Email</FormLabel>
<FormInput onChangeText={(text)=>this.setState({email:text})}/>
<FormLabel>Password</FormLabel>
<FormInput secureTextEntry={true} onChangeText={(text)=>this.setState({password:text})}/>
<Button
small
icon={{name: ‘user’, type: ‘font-awesome’}}
title=’Login’
color=’white’
backgroundColor=’#2195f3′
onPress={this._loginAsync} />
<Divider style={{ backgroundColor: ‘white’, height:5 }} />
<Button
small
icon={{name: ‘user’, type: ‘font-awesome’}}
title=’Register’
color=’white’
backgroundColor=’#9c27b0′
onPress={this._signUp} />
</Card>
</View>
);
}

_loginAsync = () => {
if(this.state.email && this.state.password){
fetch(‘http://192.168.0.103:3000/login&#8217;, {
method: ‘POST’,
headers: {
Accept: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
}),
}).then((response) => response.json()).then(async (responseJson) => {
if(responseJson.status){
await AsyncStorage.setItem(‘userToken’, responseJson.token);
await AsyncStorage.setItem(‘user’, responseJson.user.name);
await this.props.navigation.navigate(‘App’);
}else{
Alert.alert(‘Success!’,’Login Fail..’);
}
})
.catch((error) => {
Alert.alert(‘warning!’,’Login Fail..’);
console.log(error);
});
}else{
Alert.alert(‘warning!’,’Please fill User Name / Password..’);
}
};

_signUp = () => {
this.props.navigation.navigate(‘Signup’);
};
}

Signup.js


import React, {Component} from ‘react’;
import { View} from ‘react-native’;
import { Card, Button, FormLabel, FormInput, Header, Divider } from ‘react-native-elements’

export default class Signup extends React.Component {
state = {
email: ”,
password: ”,
phone: ”,
name: ”
};
static navigationOptions = {
header:null,
};

render() {
return (
<View>
<Header
centerComponent={{ text: ‘Signin’, style: { color: ‘#fff’ } }}
outerContainerStyles = {{height:50}}
/>
<Card title=”Signup”>
<FormLabel>Name</FormLabel>
<FormInput onChangeText={(text)=>this.setState({name:text})}/>
<FormLabel>Email</FormLabel>
<FormInput onChangeText={(text)=>this.setState({email:text})}/>
<FormLabel>Phone</FormLabel>
<FormInput onChangeText={(text)=>this.setState({phone:text})}/>
<FormLabel>Password</FormLabel>
<FormInput secureTextEntry={true} onChangeText={(text)=>this.setState({password:text})}/>
<Button
small
icon={{name: ‘user’, type: ‘font-awesome’}}
title=’Register’
color=’white’
backgroundColor=’#2195f3′
onPress={this._signUp} />
<Divider style={{ backgroundColor: ‘white’, height:5 }} />
<Button
small
icon={{name: ‘user’, type: ‘font-awesome’}}
title=’Login’
color=’white’
backgroundColor=’#9c27b0′
onPress={this._signInAsync} />
</Card>
</View>
);
}

_signInAsync = async () => {
this.props.navigation.navigate(‘Login’);
};

_signUp = () => {
this.props.navigation.navigate(‘App’);
};
}

Home.js

import React, {Component} from ‘react’;
import { View, AsyncStorage} from ‘react-native’;
import { createDrawerNavigator, DrawerItems, createAppContainer } from ‘react-navigation’;
import HomeScreen from ‘./main/HomeScreen’;
import { Divider,Icon, Text, Button } from ‘react-native-elements’;
import Products from ‘./main/Products’;


const RootDrawer = createAppContainer(createDrawerNavigator({
HomeScreen: {
screen: HomeScreen,
navigationOptions: {
drawerIcon: () => (<Icon name=”home” />),
}
},
‘Products’: {
screen: Products,
navigationOptions: {
drawerIcon: () => (<Icon name=’ios-information-circle’ type=’ionicon’ />),
}
}
}, {
headerMode: ‘screen’,
contentComponent: (props) => (
<View>
  
<View>
<View style={{alignItems: ‘center’}}>
<OurHead />
</View>
<Divider style={{height: 2, backgroundColor: ‘#989898’ }} />
</View>
<DrawerItems {…props} />
<Button
onPress={async () => {await AsyncStorage.clear(); this.props.navigation.navigate(‘Auth’); }}
title=”Logout”
/>
</View>
),
}));

export default class Home extends React.Component {
static navigationOptions = {
header:null,
};

render() {
return <RootDrawer />;
}

_signOutAsync = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate(‘Auth’);
};
}

class OurHead extends React.Component{
render(){
return <View><Text>Basic Authentication App</Text></View>;
}
}

main/HomeScreen.js

import React, {Component} from ‘react’;
import {View} from ‘react-native’;
import { Header, Text } from ‘react-native-elements’;

export default class HomeScreen extends React.Component {

headerSamp = () =>
    <View>
        <Header
            leftComponent={{ icon: ‘menu’, color: ‘#fff’, onPress: () => this.props.navigation.toggleDrawer() }}
            centerComponent={{ text: ‘Home’, style: { color: ‘#fff’ } }}
rightComponent={{ icon: ‘home’, color: ‘#fff’ }}
outerContainerStyles = {{height:50}}
        />
    </View>

render() {
return (
<View>
{this.headerSamp()}
<Text h3>Welcome to basic authentication app.</Text>
</View>
);
}
}

main/Products.js

import React, {Component} from ‘react’;
import { View,ScrollView, FlatList} from ‘react-native’;
import { Header, List, ListItem, Avatar } from ‘react-native-elements’;

export default class Products extends React.Component {

state = {
data:[]
}

headerSamp = () =>
    <View>
        <Header
            leftComponent={{ icon: ‘menu’, color: ‘#fff’, onPress: () => this.props.navigation.toggleDrawer() }}
            centerComponent={{ text: ‘Products’, style: { color: ‘#fff’ } }}
rightComponent={{ icon: ‘ios-information-circle’ ,type:’ionicon’, color: ‘#fff’ }}
outerContainerStyles = {{height:50}}
        />
    </View>

componentDidMount() {
fetch(‘http://frensol.com/chandu/a.php&#8217;)
.then(response => response.json())
.then(data => {this.setState({data });
});

}

renderRow ({ item }) {
return (
<ListItem
avatar={<Avatar
source={item.image && {uri: item.image}}
title={item.title}
/>}
title={item.title}
subtitle={‘INR ‘+item.mrp}
rightIcon={{name:’shopping-cart’,type:’entypo’,color:’black’}}
/>
)
}


render() {
return (
<View>
<View>
{this.headerSamp()}
</View>
<ScrollView>
<List>
<FlatList
data={this.state.data}
renderItem={this.renderRow}
keyExtractor={item => item.title}
/>
</List>
</ScrollView>
</View>
);
}
}

Git Link:  https://github.com/iamchandu/Reactnative-User-Authentication

Backend Git Link:  https://github.com/iamchandu/SampleREST-APIsUsing-Node-JWT-Sequelize

How to Create a Blog in YII2

Hi Guys,

First Install composer (click here) If you already installed leave it.

Download basic Yii2 Template and follow below commands for user migrations.

composer create-project nenad/yii2-basic-template blog

Create a sample database and give the credentials at blog/_protected/config/db.php.

Run below migration commands for user access.

cd blog/_protected

./yii migrate

./yii rbac/init

Then Create a table in the database.

CREATE TABLE `posts` (
`id` int(11) NOT NULL,
`date_time` datetime NOT NULL,
`title` varchar(60) NOT NULL,
`post` text NOT NULL,
`image` varchar(150) NOT NULL,
`status` enum(‘active’,’inactive’,’draft’) NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `posts`
ADD CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);

Create Model and CRUD for posts at http://localhost/blog/gii

Install any Text editor (I used CKEDITOR).

composer require 2amigos/yii2-ckeditor-widget

Then Create a model/UploadForm.php for upload files to the uploads folder.


Then Add/Edit views/posts/_form.php
cd2
Replace Create functionality in PostsController.php
use app\models\UploadForm;

use yii\web\UploadedFile;
public function actionCreate()

    {

        $model = new Posts();

        if ($model->load(Yii::$app->request->post())) {

            $m = new UploadForm();

            $m->file = UploadedFile::getInstance($model, 'image');

            $file_name = '';

            if ($m->file && $m->validate()) {                

                $file_name = 'uploads/' . $m->file->baseName . '.' . $m->file->extension;

                $m->file->saveAs($file_name);

            }

            $model->image = $file_name;

            if($model->validate() && $model->save()){

                return $this->redirect(['view', 'id' => $model->id]);

            }

        }
Replace below code in views/site/index.php
cd.PNG

Add the below code in views/posts/view.php
cd1
Git Link: Git

How to convert Existing database to sequelize models using sequelize-auto

If you have existing tables in the database you want to convert into sequelize models then use sequelize auto library.

Install Sequelize Auto using CLI

npm install -g sequelize-auto

Prerequisites: 

Are you using MYSQL? Run Below command. (ignore if already installed)

npm install -g mysql

Are you using Postgres? Run Below command. (ignore if already installed)

npm install -g pg pg-hstore

Keep your database server on.

Use the below command for converting to models.

sequelize-auto -h <host> -d <database> -u <user> -x [password] -p [port]  --dialect [dialect] -c [/path/to/config] -o [/path/to/models] -t [tableName] -C

Example:

sequelize-auto -h 127.0.0.1 -d sequelize -u root -x root@123 -p 3306  --dialect mysql -c c:\users\models -o c:\users\models

Have a fun with models..

Referance : https://github.com/sequelize/sequelize-auto

 

How to convert HTML Template to Angular 6 Template

First, download any HTML Template from the web. (I downloaded from here).

Create an Angular application using angular-cli

ng new angular-template

Copy all the folders and files in downloaded template past it in src/assets folder(Except HTML files).

Then Include these files into angular.json file scripts and styles section.

“styles”: [
  “src/styles.css”,
  “src/assets/css/custom.css”,
  “src/assets/vendor/bootstrap/css/bootstrap.min.css”,
  “src/assets/vendor/font-awesome/css/font-awesome.min.css”,
  “src/assets/css/fontastic.css”,
  “src/assets/css/grasp_mobile_progress_circle-1.0.0.min.css”,
  “src/assets/vendor/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.css”,
  “src/assets/css/style.default.css”
],
“scripts”: [
  “src/assets/vendor/jquery/jquery.min.js”,
  “src/assets/vendor/popper.js/umd/popper.min.js”,
  “src/assets/vendor/bootstrap/js/bootstrap.min.js”,
  “src/assets/js/grasp_mobile_progress_circle-1.0.0.min.js”,
  “src/assets/vendor/jquery.cookie/jquery.cookie.js”,
  “src/assets/vendor/chart.js/Chart.min.js”,
  “src/assets/vendor/jquery-validation/jquery.validate.min.js”,
  “src/assets/vendor/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js”,
  “src/assets/js/charts-home.js”,
  “src/assets/js/front.js”
]
Now create template layout using components
ng g component components/layout/header
ng g component components/layout/sidemenu
ng g component components/layout/footer
Now create site components
ng g component components/site/home
ng g component components/site/charts
ng g component components/site/forms
ng g component components/site/login
ng g component components/site/register
ng g component components/site/tables
Analyze downloaded code and past segregate it into the layout.
side menu code past into sidemenu.component.html
header code past into header.component.html
footer code past into footer.component.html
Main contains past in site components
Now write routing for the corresponding site in app.module.ts file
import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { HeaderComponent } from './components/layout/header/header.component';

import { SidemenuComponent } from './components/layout/sidemenu/sidemenu.component';

import { FooterComponent } from './components/layout/footer/footer.component';

import { HomeComponent } from './components/site/home/home.component';

import { ChartsComponent } from './components/site/charts/charts.component';

import { FormsComponent } from './components/site/forms/forms.component';

import { LoginComponent } from './components/site/login/login.component';

import { RegisterComponent } from './components/site/register/register.component';

import { TablesComponent } from './components/site/tables/tables.component';

import { RouterModule, Routes } from '@angular/router';

import { registerContentQuery } from '@angular/core/src/render3/instructions';

const appRoutes: Routes = [

{ path: 'login', component: LoginComponent },

{ path: 'home', component: HomeComponent},

{ path: 'register', component : RegisterComponent},

{ path: 'charts', component : ChartsComponent},

{ path: 'forms', component : FormsComponent},

{ path: 'tables', component : TablesComponent},

{ path: '',

redirectTo:'/home',

pathMatch:'full'

}

];

@NgModule({

declarations: [

AppComponent,

HeaderComponent,

SidemenuComponent,

FooterComponent,

HomeComponent,

ChartsComponent,

FormsComponent,

LoginComponent,

RegisterComponent,

TablesComponent

],

imports: [

BrowserModule,

RouterModule.forRoot(appRoutes)

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

past the below code in app.component.html

outlet.PNG

Change Links href to routerLink in sidemenu.componet.ts

Git Link:  https://github.com/iamchandu/html-to-angular6-template

Create your website at WordPress.com
Get started