Quick Contact


    Using Forms in MEAN Stack

    We learnt how to construct a model and how to utilise it in our application in the previous part. Previously, we built posts using two-way binding, which was not necessarily incorrect, but angular makes working with forms a breeze. Forms are quite useful, and we’ll employ them in the following manner:

    We’ll add the form, which is a regular html element, to our post-create.component.html file. The mat-form-field> and button are wrapped in it in the following way:

    	< mat-card>
    	< form>
    	< mat-form-field>
    	< input   
    	matInput type = "text"   
    	      [(ngModel)] = "enteredTitle">
    	< /mat-form-field>
    	< mat-form-field>
    	< textarea
    	matInput rows = "6"   
    	      [(ngModel)] = "enteredContent">< /textarea>
    	< /mat-form-field>
    	< button   
    	mat-raised-button
    	color = "primary"   
    	    (click)="onAddPost()">Save< /button>
    	< /form>
    	< /mat-card>
    	

    As a result, two-way binding isn’t required. We’ve previously included the form module, so when it detects a form element, it will construct a JavaScript object to represent it behind the scenes. We can easily register inputs as controls and save the values of these controls in the form. We can easily add validation here and submit the form to utilise the form’s data.

    By just overriding [(ngModel)] = “enteredTitle” and [(ngModel)] = “enteredContent” with ngModel, we can avoid the two-way binding. The input will be registered as a control by the ngModel. However, because angular wants to know what to call this input, we add the name property and give it whatever name we want:

    	< input   
    	matInput
    	type = "simple"   
    	name = "text"  
    	ngModel>
    	< textarea
    	matInput
    	rows = "6"  
    	name = "content "   
    	ngModel>
    	< /textarea>
    	

    We no longer need to manually call the onAddPost() function when we click the button. Because we’re utilising a form, we’ll make this button a submit button. The form will be submitted if a button of the type submit is clicked. It will cause a specific event, namely a submit event, to which we may listen, and from which we can call our onAddPost() code as follows:

    	
    < button mat-raised-button color = "primary" type = "Apply">Save Post < /button> < html ng-app="main"> < head> < meta charset="utf-8" /> < meta name="viewport" content="width=device-width, initial-scale=1.0"> < meta name="viewport" content="width=device-width" /> < title>Super Application< /title> < link href="bootstrap.css" rel="stylesheet" /> < link href="Site.css" rel="stylesheet" /> < scriptsrc="modernizr-2.6.2.js">< /script> < scriptsrc="jquery-1.10.2.js">< /script> < script src="bootstrap.js">< /script> < script src="angular.js">< /script> < script src="angular-route.js">< /script> < script src="angular-ui-router.js">< /script> < script src="angular-resource.js">< /script> < scriptsrc="/Modules/mainApp.js">< /script> < scriptsrc="/Controllers/MainController.js">< /script> < scriptsrc="/Controllers/AuthController.js">< /script> < /head> < body> < div class="navbarnavbar-inverse navbar-fixed-top"> < div class="container"> < div class="navbar-header"> < button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> < span class="icon-bar">< /span> < span class="icon-bar">< /span> < span class="icon-bar">< /span> < /button> < a class="navbar-brand" href="#/home">Application name< /a> < /div> < div class="navbar-collapse collapse"> < ul class="navnavbar-nav"> < li>< a href="#/home">Home< /a>< /li> < li>< a href="#/about">About< /a>< /li> < li>< a href="#/contact">Contact< /a>< /li> < /ul> < ul class="navnavbar-navnavbar-right"> < li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li> < li>< p class="navbar-right navbar-text" ng-hide="authenticated"> < a href="#/login">Login< /a> or < a href="#/register">Register< /a> < /p>< /li> < li>< p class="navbar-right navbar-text" ng-show="authenticated"> < a href="#" ng-click="signout()">Logout< /a> < /p>< /li> < /ul> < /div> < /div> < /div> < div class="navbarnavbar-inverse navbar-fixed-top"> < div class="container"> < div class="navbar-header"> < button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> < span class="icon-bar">< /span> < span class="icon-bar">< /span> < span class="icon-bar">< /span> < /button> < a class="navbar-brand" href="#/home">Application name< /a> < /div> < div class="navbar-collapse collapse"> < ul class="navnavbar-nav"> < li>< a href="#/home">Home< /a>< /li> < li>< a href="#/about">About< /a>< /li> < li>< a href="#/contact">Contact< /a>< /li> < /ul> < ul class="navnavbar-navnavbar-right"> < li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li> < li>< p class="navbar-right navbar-text" ng-hide="authenticated"> < a href="#/login">Login< /a> or < a href="#/register">Register< /a> < /p>< /li> < li>< p class="navbar-right navbar-text" ng-show="authenticated"> < a href="#" ng-click="signout()">Logout< /a> < /p>< /li> < div class="navbarnavbar-inverse navbar-fixed-top"> < div class="container"> < div class="navbar-header"> < button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> < span class="icon-bar">< /span> < span class="icon-bar">< /span> < span class="icon-bar">< /span> < /button> < a class="navbar-brand" href="#/home">Application name< /a> < /div> < div class="navbar-collapse collapse"> < ul class="navnavbar-nav"> < li>< a href="#/home">Home< /a>< /li> < li>< a href="#/about">About< /a>< /li> < li>< a href="#/contact">Contact< /a>< /li> < /ul> < ul class="navnavbar-navnavbar-right"> < li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li> < li>< p class="navbar-right navbar-text" ng-hide="authenticated"> < a href="#/login">Login< /a> or < a href="#/register">Register< /a> < /p>< /li> < li>< p class="navbar-right navbar-text" ng-show="authenticated"> < a href="#" ng-click="signout()">Logout< /a> < /p>< /li> < div class="container body-content"> < divui-view> < /div> < hr /> < footer> < p>My ASP.NET Application< /p> < /footer> < /div> < /body> < /html>

    Now we need to obtain access to the form’s values, which we’ll achieve with the use of a local reference. As a result, we’ll add a reference to the form and call it whatever we want:

    “onAddPost(postForm)” = “form (submit)” ngForm> #postForm = “ngForm”

    The reference was given to the onAddPost() method. We must assign the ngForm as its value to the #postForm, which will allow us access to the html element object. That is a directive, and angular connects itself to the form element implicitly.

    As a result, we must add validation to the text input and the text area by simply adding the necessary validations. This will be inserted in the following way: Angular will automatically detect this and change its form object to reflect whether it is legitimate or not.

    	< div>
    	    < div class="Cron">
    	        < h1>Node.js Application< /h1>
    	        < p class="lead">Node.js is a free Javascript framework for building great Web sites and Web applications using HTML, CSS and JavaScript.< /p>
    	        < p>< a class="btnbtn-primary btn-lg">Learn more & raquo;< /a>< /p>
    	    < /div>
    	    < div class="row">
    	        < div class="col-md-4">
    	            < h2>Getting started< /h2>
    	            < p>
    	

    ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that

    enables a clean separation of concerns and gives you full control over markup

    for enjoyable, agile development.

    	           < /p>
    	            < p>< a class="btnbtn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more & raquo;< /a>< /p>
    	        < /div>
    	        < div class="col-md-4">
    	            < h2>Get more libraries< /h2>
    	            < p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.< /p>
    	            < p>< a class="btnbtn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more & raquo;< /a>< /p>
    	        < /div>
    	< div class="row">
    	        < div class="col-md-4">
    	            < h2>Getting started< /h2>
    	            < p>
    	                ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
    	                enables a clean separation of concerns and gives you full control over markup
    	                for enjoyable, agile development.
    	            < /p>
    	            < p>< a class="btnbtn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more & raquo;< /a>< /p>
    	        < /div>
    	        < div class="col-md-4">
    	            < h2>Get more libraries< /h2>
    	            < p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.< /p>
    	            < p>< a class="btnbtn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more & raquo;< /a>< /p>
    	        < /div>
    	< div class="row">
    	        < div class="col-md-4">
    	            < h2>Getting started< /h2>
    	            < p>
    	                ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
    	                enables a clean separation of concerns and gives you full control over markup
    	                for enjoyable, agile development.
    	            < /p>
    	            < p>< a class="btnbtn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more & raquo;< /a>< /p>
    	        < /div>
    	        < div class="col-md-4">
    	            < h2>Get more libraries< /h2>
    	            < p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.< /p>
    	            < p>< a class="btnbtn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more & raquo;< /a>< /p>
    	        < /div>
    	        < div class="col-md-4">
    	            < h2>Web Hosting< /h2>
    	            < p>You can easily find a web hosting company that offers the right mix of features and price for your applications.< /p>
    	            < p>< a class="btnbtn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more & raquo;< /a>< /p>
    	        < /div>
    	    < /div>
    	< /div>
    	

    Create a new folder called Passport and a new file called passport-init.js to which you should add the following code. This is the Authentication Api that your authentication route will use.

    	var mongoose = require('mongoose');   
    	var User = mongoose.model('User');
    	varLocalStrategy   = require('passport-local').Strategy;
    	varbCrypt = require('bcrypt-nodejs');
    	module.exports = function(passport){
    
    	    passport.serializeUser(function(user, done) {
    	        console.log('serializing user:',user.username);
    	        done(null, user._id);
    	    });
    	passport.deserializeUser(function(id, done) {
    	        User.findById(id, function(err, user) {
    	            console.log('deserializing user:',user.username);
    	            done(err, user);
    	        });
    	    });
    	passport.use('login', new LocalStrategy({
    	            passReqToCallback : true
    	        },
    	        function(req, username, password, done) { 
    	        // check in mongo if a user with username exists or not
    	            User.findOne({ 'username' :  username }, 
    	                function(err, user) {
    	                    // In case of any error, return using the done method
    	                    if (err)
    	                        return done(err);
    	                    // Username does not exist, log the error and redirect back
    	                    if (!user){
    	                        console.log('User Not Found with username '+username);
    	                        return done(null, false);                 
    	                    }
    	                    // User exists but wrong password, log the error 
    	                    if (!isValidPassword(user, password)){
    	                        console.log('Invalid Password');
    	                        return done(null, false); // redirect back to login page
    	                    }
    	                    // User and password both match, return user from done method
    	                    // which will be treated like success
    	                    return done(null, user);
    	                }
    	            );
    	        }
    	    ));
    	passport.use('signup', new LocalStrategy({
    	            passReqToCallback : true // allows us to pass back the entire request to the callback
    	        },
    	        function(req, username, password, done, email, role) {
    	// find a user in mongo with provided username
    	            User.findOne({ 'username' :  username }, function(err, user) {
    	                // In case of any error, return using the done method
    	                if (err){
    	                    console.log('Error in SignUp: '+ err);
    	                    return done(err);
    	                }
    	                // already exists
    	passport.serializeUser(function(user, done) {
    	        console.log('serializing user:',user.username);
    	        done(null, user._id);
    	    });
    	passport.deserializeUser(function(id, done) {
    	        User.findById(id, function(err, user) {
    	            console.log('deserializing user:',user.username);
    	            done(err, user);
    	        });
    	    });
    	passport.use('login', new LocalStrategy({
    	            passReqToCallback : true
    	        },
    	        function(req, username, password, done) { 
    	        // check in mongo if a user with username exists or not
    	            User.findOne({ 'username' :  username }, 
    	                function(err, user) {
    	                    // In case of any error, return using the done method
    	                    if (err)
    	                        return done(err);
    	                    // Username does not exist, log the error and redirect back
    	                    if (!user){
    	                        console.log('User Not Found with username '+username);
    	                        return done(null, false);                 
    	                    }
    	                    // User exists but wrong password, log the error 
    	                    if (!isValidPassword(user, password)){
    	                        console.log('Invalid Password');
    	                        return done(null, false); // redirect back to login page
    	                    }
    	                    // User and password both match, return user from done method
    	                    // which will be treated like success
    	                    return done(null, user);
    	                }
    	            );
    	        }
    	    ));
    	passport.use('signup', new LocalStrategy({
    	            passReqToCallback : true // allows us to pass back the entire request to the callback
    	        },
    	        function(req, username, password, done, email, role) {
    	// find a user in mongo with provided username
    	            User.findOne({ 'username' :  username }, function(err, user) {
    	                // In case of any error, return using the done method
    	                if (err){
    	passport.serializeUser(function(user, done) {
    	        console.log('serializing user:',user.username);
    	        done(null, user._id);
    	    });
    	passport.deserializeUser(function(id, done) {
    	        User.findById(id, function(err, user) {
    	            console.log('deserializing user:',user.username);
    	            done(err, user);
    	        });
    	    });
    	passport.use('login', new LocalStrategy({
    	            passReqToCallback : true
    	        },
    	        function(req, username, password, done) { 
    	        // check in mongo if a user with username exists or not
    	            User.findOne({ 'username' :  username }, 
    	                function(err, user) {
    	                    // In case of any error, return using the done method
    	                    if (err)
    	                        return done(err);
    	                    // Username does not exist, log the error and redirect back
    	                    if (!user){
    	                        console.log('User Not Found with username '+username);
    	                        return done(null, false);                 
    	                    }
    	                    // User exists but wrong password, log the error 
    	                    if (!isValidPassword(user, password)){
    	                        console.log('Invalid Password');
    	                        return done(null, false); // redirect back to login page
    	                    }
    	                    // User and password both match, return user from done method
    	                    // which will be treated like success
    	                    return done(null, user);
    	                }
    	            );
    	        }
    	    ));
    	passport.use('signup', new LocalStrategy({
    	            passReqToCallback : true // allows us to pass back the entire request to the callback
    	        },
    	        function(req, username, password, done, email, role) {
    	// find a user in mongo with provided username
    	            User.findOne({ 'username' :  username }, function(err, user) {
    	                // In case of any error, return using the done method
    	                if (err){
    	                    console.log('Error in SignUp: '+ err);
    	                    return done(err);
    	                }
    	                    console.log('Error in SignUp: '+ err);
    	                    return done(err);
    	                }
    	                if (user) {
    	                    console.log('User already exists with username: '+username);
    	                    return done(null, false);
    	                } else {
    	                    // if there is no user, create the user
    	                    varnewUser = new User();
    	                    // set the user's local credentials
    	                    newUser.username = username;
    	                    newUser.password = createHash(password);
    	                    newUser.email = req.body.email;
    	                    newUser.role = req.body.role;
    	                    // save the user
    	                    newUser.save(function(err) {
    	                        if (err){
    	                            console.log('Error in Saving user: '+err);  
    	                            throw err;  
    	                        }
    	                        console.log(newUser.username + ' Registration succesful');    
    	                        return done(null, newUser);
    	                    });
    	                }
    	            });
    	        })
    	    );
    	varisValidPassword = function(user, password){
    	        returnbCrypt.compareSync(password, user.password);
    	    };
    	    // Generates hash using bCrypt
    	    varcreateHash = function(password){
    	        returnbCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
    	    };
    	};
    	
    Add a new file server now. js should be placed in the root directory because it will be our main beginning file.
    	//server.js
    	//adding opensource modules to application 
    	var express = require('express'); //express 
    	var path = require('path'); //for refering physical files here
    	var logger = require('morgan'); 
    	varcookieParser = require('cookie-parser'); //for maintain sessions
    	varbodyParser = require('body-parser'); //for parsing json
    	varbcrypt = require('bcrypt-nodejs'); 
    	var passport = require('passport'); //Using passportjs for authentication
    	varLocalStrategy = require('passport-local').Strategy; //using passport strategy
    	var session = require('express-session'); //for maintaining sessions
    	var mongoose = require('mongoose'); //for mongodb, database
    	varmodels_user = require('./Angular/Models/user.js'); // refering models in server.js
    
    	//connection database
    	mongoose.connect('mongodb://localhost/AngularizeApp');
    
    	//import the routers
    	var router = require('./Routes/router');
    	var authenticate = require('./Routes/authentication')(passport);
    
    	//for using express throughout this application
    	var app = express();
    
    	//tell node that My application will use ejs engine for rendering, view engine setup
    	app.set('views', path.join(__dirname, 'Views'));
    	app.set('view engine', 'ejs');
    
    	//tell node the global configuration about parser,logger and passport
    	app.use(cookieParser());
    	app.use(logger('dev'));
    	app.use(session({
    	  secret: 'keyboard cat'
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    
    
    	varinitPassport = require('./Passport/passport-init');
    	initPassport(passport);
    
    	var server = app.listen(3000, function () {
    	  var host = server.address().address;
    	  var port = server.address().port;
    	  console.log('Example app listening at http://%s:%s', host, port);
    	});
    
    	//exporting this application as a module
    	module.exports = app;
    
    	//connection database
    	mongoose.connect('mongodb://localhost/AngularizeApp');
    
    	//import the routers
    	var router = require('./Routes/router');
    	var authenticate = require('./Routes/authentication')(passport);
    
    	//for using express throughout this application
    	var app = express();
    
    	//tell node that My application will use ejs engine for rendering, view engine setup
    	app.set('views', path.join(__dirname, 'Views'));
    	app.set('view engine', 'ejs');
    
    	//tell node the global configuration about parser,logger and passport
    	app.use(cookieParser());
    	app.use(logger('dev'));
    	app.use(session({
    	  secret: 'keyboard cat'
    
    	//connection database
    	mongoose.connect('mongodb://localhost/AngularizeApp');
    
    	//import the routers
    	var router = require('./Routes/router');
    	var authenticate = require('./Routes/authentication')(passport);
    
    	//for using express throughout this application
    	var app = express();
    
    	//tell node that My application will use ejs engine for rendering, view engine setup
    	app.set('views', path.join(__dirname, 'Views'));
    	app.set('view engine', 'ejs');
    
    	//tell node the global configuration about parser,logger and passport
    	app.use(cookieParser());
    	app.use(logger('dev'));
    	app.use(session({
    	  secret: 'keyboard cat'
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    	

    We have our form, and now we must construct the backend for it, which we will accomplish by creating routes that will allow us to do so. Mongoose will also be used to handle new users and save them in the database. All of this will be covered in the next part.

    Copyright 1999- Ducat Creative, All rights reserved.