Angular 5 vs Angular 6

Angular 6 Form submit Example

Create Anular6 project – using below command
ng new project_name

Go to the project - project_name directory

Create the user component – using below command
ng g component user

Create the user class
export class User {
   public id: number;
   public name: string;
   public age: string;
   public url?: string
}


Create user component - user.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from  '@angular/common/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import {User} from '../user;

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  model = new User();//user model object

  constructor() { }

  ngOnInit() {
  }

  submit(){
    alert(JSON.stringify(this.model));
  }
}

Bind the user model with user form - user.component.html
<link rel="stylesheet" href="https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css">

<div class="container">
  <h1>Add User Form</h1>
  <form (submit)="submit()">
    <div class="form-group">
      <label for="title">UserId</label>
      <input type="text" class="form-control" id="title" required [(ngModel)]="model.id" name="title">
    </div>
    <div class="form-group">
      <label for="author">User Name</label>
      <input type="text" class="form-control" id="author" required [(ngModel)]="model.name" name="author">
    </div>
    <div class="form-group">
      <label for="url">URL Blog</label>
      <input type="text" class="form-control" id="url" [(ngModel)]="model.url" name="url">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
   </form>

   <div> Result - {{model | json}}</div>
 </div>

Setup the component and routing in NgModule class
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';//#1
import { RouterModule, Routes } from '@angular/router'; //#2

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

@NgModule({
  declarations: [
    AppComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,//#1
    RouterModule.forRoot([
      { path: 'user-link', component: UserComponent } //#2
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Setup the routerLink and router-outlet in app.component.htnl
<a routerLink="/user-link" routerLinkActive="active">link</a>
<router-outlet></router-outlet>


Result –


ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^