Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications.

free-ebook-for-react-js-beginners


This react.js ebook include the following things. I haven't cover the topic in detail and you can go through the below topic and easily understand the react.


  1. Overview.
  2. Why we used react.js
  3. Why react.js is a great choice to start.
  4. Why react is great performer.
  5. Features of react.
    1. Components
    2. Virtual DOM
    3. Declarative
    4. Unidirectional data flow
    5. Isomorphic friendly
    6. JSX
  6. How to create component and jsx into react.
  7. React props and states why we used that.
  8. what are the testing frameworks we need in react ex. chai,mocha,jest,enzyme
  9. A few testing examples of react.js testing component.
  10. Usefull links for testing and learning.



Apache SSL Config

In this article i'll show you how to configure your website with ssl. It is also captured the user who go directly mydomain.com without www. Please note that this requires two sets of ssl certificates, unless you have wildcard ones.

In ubuntu 16.04 the file location is /etc/apache2/sites-available/default-ssl.conf  and enabled by running a2ensite default-ssl.conf . Also, don't forget to enable ssl with sudo a2enmod ssl.

# www.mydomain.com
<VirtualHost *:443>
    ServerName www.mydomain.com

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/www.mydomain.com/cert.pem
    SSLCertificateKeyFile /etc/apache2/ssl/www.mydomain.com/private.pem
    SSLCertificateChainFile /etc/apache2/ssl/www.mydomain.com/chain.pem

    ServerAdmin webmaster@localhost

    DocumentRoot /var/www/my-site/public_html
    <Directory /var/www/my-site/public_html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        allow from all
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

# capture users going to mydomain.com without the www.
<VirtualHost *:443>
    ServerName mydomain.com

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/mydomain.com/cert.pem
    SSLCertificateKeyFile /etc/apache2/ssl/mydomain.com/private.pem
    SSLCertificateChainFile /etc/apache2/ssl/mydomain.com/chain.pem

    ServerAdmin webmaster@localhost

    DocumentRoot /var/www/my-site/public_html
    <Directory /var/www/my-site/public_html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        allow from all
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Reverse Proxy serve different folder NGINX

In this post i'll show you how we can configure NGINX to serve applications form the different directories. I have two application both are running at different ports, 8080 and 8090. I want to expose those APIs just like they are serving from a single source.

I want to expose those APIs just like they are serving from a single source. nginx config file /etc/nginx/site-available

server {
 
    listen              443 ssl;
    server_name         app.yourapp.com;
    ssl_certificate     /etc/nginx/ssl/app.yourapp.com.crt;
    ssl_certificate_key /etc/nginx/ssl/app.yourapp.com.key;
 
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
 
    location /v1/ {
            proxy_pass http://localhost:8090;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }
 
    location / {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
 }
}

If you add multiple application at same host. we have configured NGINX reverse Proxy for two apps using location block, v1 is listening at 8090 and / is listening at 8080.

You can access the app : https:://app. yourapp.com and https:://app.yourapp.com/v1

If you are new to nginx server so you can check this link to use nginx.

Install Typescript in ubuntu

For now I just know of the one main way to install Typescript, but as and when I find out more ways, such as a PPA, I'll post them here.

sudo apt update && sudo apt install node-typescript -y

Finally Clause in PHP

PHP has supported the finally clause.Finally will executed after a try block no matter what is your condition. if the try block threw an exception or not.

<?php

try 
{
    print "Start executing try block BEFORE exception." . PHP_EOL;
    throw new Exception("This is my exception");
    print "Executing try block AFTER exception thrown." . PHP_EOL;
} 
catch (Exception $e) 
{
    print "Executing the catch block." . PHP_EOL;
} 
finally 
{
    print "Executing 'finally' block." . PHP_EOL;
}

print "Executing code after finally." . PHP_EOL;

Start executing try block BEFORE exception.
Executing the catch block.
Executing 'finally' block.
Executing code after finally.

so finally is executed even if exception occurred. we can understand this with the below two examples.

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
}

example(); // Will not execute if throw_exception throws an ExceptionTypeB

But this will execute.

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
} finally {
    some_code(); // Will be execute even if throw_exception throws an ExceptionTypeB
}

As you can see the finally block is still executed, even though something went wrong within our exception handling.

Calling abstract classes in TypeScript

Abstraction is an Object Oriented programming concept whereby a class can specify how an inherited class should implement the class itself, including any abstract methods specified.The concept of abstraction is we are hiding the complexity of the implementation from inherited classes and we allow them to implement the functionality themselves . 

Abstraction can be achieved by using the abstract keyword - which can be applied to both classes and methods specified in classes.

Let's take an example of abstract class :

abstract class Warrior {
  readonly name: string;
  public weapon: string;
  constructor(name: string) {
    this.name = name;
  }

  abstract arm(weapon: string): void;
}


If we now attempt to instantiate this class we'll get an error:

const peter = new Warrior('Peter, the Nomad'); // Cannot create an instance of the abstract class 'Warrior'.

Now we need to implement the abstract class then we need to create a subclass and extend it using the extends keyword.

class SuperWarrior extends Warrior {
  constructor(name: string) {
    super(name);
  }
  arm(weapon: string): void {
    console.log(`${this.name} is a super warrior fighting with ${weapon}`);
  }
}


Now we have a subclass we can create our warriors.

const warrior = new SuperWarrior('John, the Nomad');
warrior.arm('lance'); // John, the Nomad is a super warrior fighting with lance



we can also utilise Interfaces and implement them for classes

interface IWarrior {
  name: string;
  weapon: string;
  arm(weapon: string): void;
}
abstract class Warrior implements IWarrior {
  readonly name: string;
  public weapon: string;
  constructor(name: string) {
    this.name = name;
  }

  abstract arm(weapon: string): void;
}

class SuperWarrior extends Warrior {
  constructor(name: string) {
    super(name);
  }
  arm(weapon): void {
    console.log(`${this.name} is a super warrior fighting with ${weapon}`);
  }
}

const warrior: IWarrior = new SuperWarrior('John, the Nomad');
warrior.arm('lance');

Install Machine Learning Tool in Python

In this article i will show you how to install tensorflow in python3. It's quite easy in ubuntu to set the tensorflow which is an open-source machine learning software.

Run the following commands/script to get tensorflow (CPU only) installed on your Ubuntu 16.04 server.

# Install necessary python packages.
sudo apt-get install python3-pip python3-dev -y

# Upgrade pip using this
pip3 install --upgrade pip

# Install tensorflow (cpu only)
pip3 install tensorflow

If you want to use an NVIDIA GPU for tensorflow then run this instead:

# Install necessary python packages.
sudo apt-get install python3-pip python3-dev -y

# Upgrade pip
pip3 install --upgrade pip

# Install tensorflow with GPU support
pip3 install tensorflow-gpu

That seemed a little too easy, so let's just write a small test script that uses the tensorflow library that we have installed it correctly:

#!/usr/bin/python3
import tensorflow as tf
hello = tf.constant("Hello, Tensflow!")
sess = tf.Session()
print(sess.run(hello))

If you execute this output should be :

b'Hello, Tensflow!'

Now you have successfully installed tensorflow in your system. If you want to read more about the tensorflow then follow the link.


Symfony console command basics

Let's take a look on symfony command.It very easy in symfony to check the existing command and list of all commands. Execute the following to check all the existing feature commands in console.

symfony console commands basics


run this command in your root directory,

php bin/console


You will see a list of existing commands. Each supported command has a short details. Each of the standard commands come with help, so I will not be describing each of them here, but it is worth to mention a few commonly used ones:

php bin/console: cache:clear

Symfonys in production store more data in caching. Therefore, if you need to change values within a template (Twig) or within configuration files while in production mode, you will need to clear the cache. Cache is also one of the reasons why it’s worth to work in the development mode.

php bin/console container:debug

Displays all configured public services in symfony.

php bin/console router:debug

It will displays all routing configuration along with method, scheme, host, and path.

php bin/console security:check

Checks your composer and packages version against known security vulnerabilities. You should run this command regularly.

Yii2 custom pagination for gridview

Pagination is the process of dividing a document into discrete pages, either electronic pages or printed pages.In this article we discussed the Yii2 pagination how we used the pagination under yii2 framework.

There are two ways we can use the pagination in Yii2.

  • Simple Pagination
  • Custom Pagination



Add this function in your controller file.

function actionIndex()
{
    $query = User::find()->where(['status' => 1]);
    $countQuery = clone $query;
    $pages = new Pagination(['totalCount' => $countQuery->count()]);
    $models = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();

    return $this->render('index', [
         'models' => $models,
         'pages' => $pages,
    ]);
}

Now come to view part index.php file.

foreach ($models as $model) {
    // display $model here
}
// display pagination
echo LinkPager::widget([
    'pagination' => $pages,
]);

Custom Pagination :

LinkPager is handling the pagination link with properties. Here we customized the link property.
so i have create CustomPagination class in app/components folder and set namespace as app/components.We removed the link and added onclick attribute in every pagination link.



<?php
namespace app\components;

use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\base\Widget;
use yii\data\Pagination;

class CustomPagination  extends \yii\widgets\LinkPager
{
    public function init()
    {
        parent::init();
    }

    public function run()
    {
        parent::run();
    }

    protected function renderPageButton($label, $page, $class, $disabled, $active)
    {
        $options = ['class' => $class === '' ? null : $class];
        if ($active) {
            Html::addCssClass($options, $this->activePageCssClass);
        }
        if ($disabled) {
            Html::addCssClass($options, $this->disabledPageCssClass);

            return Html::tag('li', Html::tag('span', $label), $options);
        }
        $linkOptions = $this->linkOptions;
        $linkOptions['data-page'] = $page;
        $linkOptions['onclick']='submit_form('.$page.')';

        return Html::tag('li', Html::a($label, '#pagination', $linkOptions), $options);
    }
}

Now in Controller.php .

public function index(){
    $query = Tablereport::find();
    $countQuery = clone $query;
    
    $pages = new Pagination(['totalCount' => $countQuery->count()]);
    
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
     return $this->render('GridView', [
         'dataProvider' => $dataProvider,
         'pages' => $pages,
    ]);
}

GridView.php
Using 'layout' properties, we can remove the basic link pager.

<?php
use yii\helpers\Html;
use yii\grid\GridView;
use app\components\CustomPagination;
?>
<div class="report-index">
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        //'filterModel' => $searchModel,
         'layout' => "{summary}\n{items}",
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'report_name',
            'report_table',
            'report_query:ntext',
            'created_on',
            // 'created_by',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

    <div id="custom-pagination">
        <?php
            echo CustomPagination::widget([
                'pagination' => $pages,
            ]);
        ?>
    </div>
</div>

How to redirect non Whitelisted IPs in NGINX

We are using the geo module for NGINX to allow specific IPs through,  and redirect all others to a page letting them know that access has been restricted and that they don't have access. This was done using Ubuntu 16.04, but should be similar for other linux distros.

Steps:

You have to install NGINX first.

sudo apt install nginx -y

Now create a file for single configuaration that has the IPs in it that all the site configs will include.

sudo vim /etc/nginx/whitelisted-ips.conf
geo $bad_user {
    default 1;

    # My Home IP
    192.168.1.1/22 0;

    # My Workspace IP
    192.168.1.2/22 0;
}

Create a configuration for the website you wish to filter for.

sudo vim /etc/nginx/sites-enabled/mywebsite.com;

include /etc/nginx/whitelisted-ips.conf

server {
    listen 80;

    # order of specify is important if allowing aliases
    server_name mywebsite.com;

    access_log /var/log/nginx/mywebsite.com-access.log;

    location / {
        if ($bad_user) {
            rewrite ^ http://myother.site.com/access-restricted-landing-page;
        }

        # include the default proxy_params conf in order 
        # to set headers for proxying.
        include /etc/nginx/proxy_params;

        # Send the user off to the backend server. 
        # They will only get here if they are whitelisted.
        proxy_pass http://xxx.xxx.xxx.xxx;
    }
}

Now test your configurations by running:

sudo nginx -t

If it gives you the all clear, have nginx use the configuration with:

sudo nginx -s reload

Now access the backend webserver (http://xxx.xxx.xxx.xxx in this case) is not accessible by the user just going to the IP, or if the user was to falsify their own DNS to go to that IP.The best way to do this is probably to have it's firewall only accept connections from the proxy.

how to install ansible in ubuntu

Ansible is an open source, powerful automation software for configuring, managing and deploying software applications on the nodes without any downtime just by using SSH. This is the server that should act as the "controller" of other servers. You do not need to install ansible on the "slaves" that get controlled.


Native Package System
sudo apt update && sudo apt install ansible -y

Install from PPA
This will install ansible version 2.1.2.0.

sudo apt-get install software-properties-common python-software-properties -y
sudo add-apt-repository ppa:ansible/ansible -y
sudo apt-get update && sudo apt-get install ansible -y


RabbitMQ deployment With Docker

You can use to deploy your own RabbitMQ server using docker. There are several ways to configure your deployment, but this is a generic method to configure RabbitMQ in docker.

  • Deploy with the web interface to manage your server.
  • Specify a username and password for managing the server.
  • Use a volume to keep state across containers being created/destroyed.
  • Uses port 80 for the web interface so that you can just go to the hostname in your browser without having to enter a port number.

Server Requirements : 
  • 512 MB of RAM
  • 1 vCPU
#!/bin/bash

# Settings
CONTAINER_NAME="rabbitmq-container"
DEFAULT_USER="root"
DEFAULT_PASSWORD="yourpassword"
CLUSTER_COOKIE="random"
HOSTNAME="rabbitmq.yourdomain.com"

# Don't change below this line.
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
docker kill $CONTAINER_NAME
docker rm $CONTAINER_NAME

docker run -d \
--restart=always \
--hostname $HOSTNAME \
--name $CONTAINER_NAME \
-p 80:15672 \
-p 4369:4369 \
-p 5671:5671 \
-p 5672:5672 \
-p 15671:15671 \
-p 25672:25672 \
-e RABBITMQ_ERLANG_COOKIE="$CLUSTER_COOKIE" \
-e RABBITMQ_DEFAULT_USER="$DEFAULT_USER" \
-e RABBITMQ_DEFAULT_PASS="$DEFAULT_PASSWORD" \
-v $DIR/rabbitmq-state:/var/lib/rabbitmq \
rabbitmq:3-management



How to restart ubuntu gui.

Sometime my GUI locks up and becomes unresponsive.This is usually shown by something like compiz eating 100% CPU usage in htop when I SSH in.

The easiest way to resolve this is to run this command to restart the lightdm service which handles the GUI.Note that you will be taken back to the login screen.


sudo service lightdm restart


Docker - Login into new TTY with a Running Container

Sometime we need to access the container from another shell in order to run some tail -f log/* or examine some files. so this post will help you to run a another shell with same container id.

You can run a new tty using docker exec -it [container-id] bash command.

To make life easier, I created the script below and placed it at /usr/bin/docker-tty.

#!/bin/bash 

EXPECTED_NUM_ARGS=1;

if [ "$#" -ne $EXPECTED_NUM_ARGS ]; then
    # user didn't specify which container ID, assume the latest one
    CONTAINER_ID=`/usr/bin/docker ps -q --no-trunc | /bin/sed -n 1p`
    /usr/bin/docker exec -it $CONTAINER_ID env TERM=xterm bash
else
    # enter the container the user specified
    /usr/bin/docker exec -it $1 env TERM=xterm bash
fi

Now make it executeable:

sudo chmod +x /usr/bin/docker-tty

Now you can just run docker-tty $CONTAINER_ID to enter into new tty. but if you want to enter the last container you spawned.so you run the command docker-tty without having to lookup the id.

Introducing Laravel Horizon dashboard for queue

Laravel Horizon is an open source software which turbo charges Laravel Redis queues with a beautiful dashboard and code-driven configuration system.The Horizon dashboard is a single page application which is build in using Vue.JS. It provide real-time insights into queue workloads, failed jobs, recent jobs, job retries, throughput and runtime metrics, and process counts.
and it’s totally open source and free for entire Laravel community.


According to Taylor Otwell:

“I built Horizon to scratch my own itch. I need deep insight into my queue throughput, performance, wait times, failures. And, when a customer has a problem, Horizon allows me to quickly find the job that failed.”


Read here : medium.com

Implementing authentication security token in symfony

Symfony provide a guard authentication bundle in which with API keys we handle the authentication responses and user credentials.you want to apply token based authentication system in Symfony and authenticate users through an API key. In this article i will show you how can you work with Guard and authenticate users via API tokens.

symfony authentication security token



1. Create User class & Provider class.

Create a user entity class which implements UserInterface and user provider. For authentication it depends on UserProvider when user submit the information the provider values are checked and further verification of password takes place.

User Entity : 

<?php

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**

* @ORM\Entity

* @ORM\Table(name="user")

*/

class User implements UserInterface

{

   /**

    * @ORM\Id

    * @ORM\GeneratedValue

    * @ORM\Column(type="integer")

    */

   private $id;

   /**

    * @ORM\Column(type="string", unique=true)

    */

   private $username;

   /**

    * @ORM\Column(type="string", unique=true)

    */

   private $email;

   /**

    * @ORM\Column(type="string")

    */

   private $password;

   /**

    * @ORM\Column(type="json_array")

    */

   private $roles = array();

   /**

    * @ORM\Column(type="string", unique=true)

    */

   private $apiToken;

   public function getId()

   {

       return $this->id;

   }

   public function getUsername()

   {

       return $this->username;

   }

   public function setUsername($username)

   {

       $this->username = $username;

   }

   public function getEmail()

   {

       return $this->email;

   }

   public function setEmail($email)

   {

       $this->email = $email;

   }

   public function getPassword()

   {

       return $this->password;

   }

   public function setPassword($password)

   {

       $this->password = $password;

   }

   /**

    * Returns the roles or permissions granted to the user for security.

    */

   public function getRoles()

   {
       $roles = $this->roles;

       // guarantees that a user always has at least one role for security

       if (empty($roles)) {

           $roles[] = 'ROLE_USER';

       }

       return array_unique($roles);

   }

   public function setRoles($roles)

   {
       $this->roles = $roles;

   }

   /**

    * Returns the salt that was originally used to encode the password.

    */

   public function getSalt()

   {
       return;

   }

   /**

    * Removes sensitive data from the user.

    */

   public function eraseCredentials()

   {

       // if you had a plainPassword property, you'd nullify it here

       // $this->plainPassword = null;

   }

   /**

    * @param string $apiToken

    */

   public function setApiToken($apiToken)

   {

       $this->apiToken = $apiToken;

   }

}


2. You need to register the provider in security.yml

providers:

       api_key_user_provider:

           entity:

               class: AppBundle:User

               property: apikey


3. Now you need to install Guard Bundle.

Guard provides different layers of authentication.It first introduced in symfony 2.8 and after that it’s now become a part of symfony core. With Guard authentication process is handled by only one class: an Authenticator.

You can also install the Guard with composer :

composer require symfony/security-guard

4. Create an Authenticator Class.

Create a new authenticator class which implements GuardAuthenticatorInterface extends the AbstractGuardAuthenticator.This class will read the api token in header request and find the respective user.

This class will read the api token in header request and find the respective user.

Create a new file: (src/AppBundle/Security/TokenAuthenticator.php)

<?php
namespace AppBundle\Security;



use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;


class TokenAuthenticator extends AbstractGuardAuthenticator

{

   /**
    * Called on every request. Return whatever credentials you want to
    * be passed to getUser(). Returning null will cause this authenticator
    * to be skipped.
    */

   public function getCredentials(Request $request)

   {
       if (!$token = $request->headers->get('X-AUTH-TOKEN')) {

           // No token?

           $token = null;

       }

       // What you return here will be passed to getUser() as $credentials

       return array(

           'token' => $token,

       );

   }

   public function getUser($credentials, UserProviderInterface $userProvider)

   {
       $apikey = $credentials['token'];

       if (null === $apikey) {

           return;

       }
       // if null, authentication will fail

       // if a User object, checkCredentials() is called

       return $userProvider->loadUserByUsername($apikey);

   }

   public function checkCredentials($credentials, UserInterface $user)

   {
       // check credentials - e.g. make sure the password is valid

       // no credential check is needed in this case



       // return true to cause authentication success

       return true;

   }

   public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)

   {

       // on success, let the request continue

       return null;

   }

   public function onAuthenticationFailure(Request $request, AuthenticationException $exception)

   {

       $data = array(

           'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

           // or to translate this message

           // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())

       );

       return new JsonResponse($data, Response::HTTP_FORBIDDEN);

   }

   /**

    * Called when authentication is needed, but it's not sent

    */

   public function start(Request $request, AuthenticationException $authException = null)

   {
       $data = array(

           // you might translate this message

           'message' => 'Authentication Required'

       );

       return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);

   }

   public function supportsRememberMe()

   {
       return false;

   }

}

You can read the whole method of guard here

5. Configuring The Authenticator.

To configure the authenticator I need to update the firewall:

security:
   # ...
   firewalls:
       # ...
       main:
           anonymous: ~
           logout: ~
           guard:
               authenticators:
                   - AppBundle\Security\TokenAuthenticator



After that register the authenticator as a service in service.yml:

services:
   api_key_authenticator:
       class: AppBundle\Security\TokenAuthenticator
       arguments: ["@router"]


Everthing is done now check the response in url.

curl -H "X-AUTH-TOKEN: username" http://yourappurl.com

How to use template in angular component

Angular template is a mix of custom elements and HTML.In this post i will show you how we used the it inline and external template.

There are two ways we can add template in our component.

1. Inline Templates : Inline templates are directly in the component decorator. Template literals with back-ticks allow multi-line strings.


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

@Component({
    selector: 'app-inline-template-example',
    template: `
        <h2>Inline Template</h2>
        <p>
            Here your text
        </p>`
})
export class InlineTemplateComponent {}

2. External Template : External templates define the HTML in a separate file and reference the file in templateUrl.


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

@Component({
    selector: 'app-external-template-example',
    templateUrl: 'external.html'
})
export class ExternalTemplateComponent {}

You can also follow the official style guide of angular html template.

Angular 5 Template Expressions and Interpolation

Interpolation use the {{ expression }} to render the value to the template.Interpolation uses template expressions in double curly braces to display data from the component class and template reference variables.

Interpolation with Curly Braces :

{{ }} contain template expressions which allow us to read object values from component properties.Double curly braces are similar to javascript and include feature such as ternery operator,concatenation and airthmetic.


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

@Component({
  selector: 'app-employee',
  template: `
    <h2>{{heading}}</h2>
    <p>
      Name: {{employee.sex === 'm' ? 'Mr' : 'Ms'}}
      {{employee.name.first + ' ' + employee.name.surname}}
    </p>`
})
export class EmployeeComponent {

  heading = 'Employee Details';

  employee: any = {
    name: {
      first: 'John',
      surname: 'Doe'
    },
    sex: 'm'
  };
}

How to install symfony 4 php framework

Symfony 4 was released in last year so it introducing a new workflow based on the tool "Symfony Flex", that replaces and improves the Symfony Installer and the Symfony Standard Edition, it enables a distribution composition based project instead of inheritance. According to Symfony developers, this new way to work is easier, more flexible, and even powerful.

Install Symfony4 in ubuntu


The first thing that you need to know is that as usual with a major release of Symfony, the project structure has changed. 

Bundles are now loaded in the /config/bundles.php file instead of the Kernel. Symfony 4 is using the  environment variables file instead of app/config/parameters.yml

There are many changes comparing it with Symfony 3 but you can easily upgrade your symfony 3 application to 4 follow the url. here

Lets create a hello world using symfony framework.

Requirements : 
  • Composer should be installed in your machine.
  • PHP >= 7.1: Symfony requires at least this version of PHP to work.
steps to create a project:

To create your first Symfony 4 project, following the standard documentation, we won't use the Symfony Installer or the standard edition, but with the flex version that can be downloaded from the symfony/skeleton package. This package contains the basic structure for any Symfony 4 based project and can be installed using the following command:


SymfonyWorld is your project name you can change it according to your project.


composer create-project symfony/skeleton SymfonyWorld

Switch to directory :

cd SymfonyWorld

Run the command.
php bin/console server:run

Now navigate to the browser and open http://127.0.0.1:8000 and check the hello from the symfony.







String interpolation in angular 5

In this lesson i will show you how to change the content of your component dynamically using angular.

String interpolation in angular 5


Note : when we are mention angular.js it means we are talking about angular 1 and angular means the new version of angular which is 2 and now 5.

After installing angular 5 in your machine lets create a new component.


ng generate component server

or 

ng g c server

it will generate the file in you src/app/server directory.

Now open server.component.ts

In this file we will change the serverId and serverStatus dynamically . Here i take these argument value static but it change dynamically also.

here we create the properties by specifying the types using TypeScript in this way.

    serverId : number = 10;
    serverStatus : string = 'offline';


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

@Component({
    selector:'app-server',
    templateUrl:'./server.component.html',
})
export class ServerComponent {
    serverId : number = 10;
    serverStatus : string = 'offline';

    getServerStatus(){
        return this.serverStatus;
    }

}

In server.component.html, we will be using double curly braces {{}} which will enable us to type TS expressions in between. {{}} is used for the string interpolation in angular.

open the server.component.html

<p>The {{ 'server' }} component id is {{ serverId }} and status {{ getServerStatus() }}.</p>

Now string interpolations display the value {{ 'server' }} and {{ serverId }} . we can use {{ 'server' }} or without '' {{ server }}.

The next thing is to add the component tag in your main app.component.html file.


<app-server></app-server> 

Now Run your app and navigate to the browser.

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular