I'm trying to simply display a checkbox in a bootstrap drop down but its just displays as blank. It's a generic dropdown. Below I've shown my code and a few screenshots. I feel like this is kinda bizarre and not sure if this is an angular thing or not.
stackblitz url:
https://stackblitz.com/edit/angular-45uk59
Code:
<div class="form-group">
<label *ngIf='label!=null' for={{id}}>{{label}}}</label>
<select class="form-control" id="{{id}}">
<option value="-1"></option>
<option *ngFor="let item of content; let i = index" value="{{item.value}}">
<span *ngIf='hasCheckbox === true'>
<!-- <input type="checkbox" id="{{id}}_i" />   -->
<input type="checkbox" name="item.text[{{i}}]" value="{{item.value}}" />
</span>
{{item.text}}
</option>
</select>
</div>
Component:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {
content: DropDownContent[] = new Array<DropDownContent>();
#Input() hasCheckbox:boolean = false;
#Input() label:string = null;
#Input() id:string = 'defaultId'
#Input() selectedId:number = -1;
#Input() size: 'lg' | 'md' | 'sm' = 'lg';
#Input() set contentInput(contentInput: DropDownContent[]) {
if (contentInput) {
this.content = contentInput.map(data => {
return <DropDownContent>(data);
});
console.log(this.content);
} else {
//?
}
}
constructor() { }
ngOnInit() {
console.log(this.id)
}
}
export class DropDownContent {
value: number;
text: string;
}
Screenshot:
Code:
You could wrap divs in a form like sort of hack thing. not exactly what you want but it works:
HTML
<form>
<div class="selectthingy">
<div class="Box" onclick="showMeTheBoxes()">
<select>
<option>Select an option</option>
</select>
<div class="checkboxselect"></div>
</div>
<div id="boxes_wrapper">
<label for="one">
<input type="checkbox" id="1" />SALSA</label>
<label for="two">
<input type="checkbox" id="2" />MUMBA</label>
<label for="three">
<input type="checkbox" id="3" />CHICKEN DANCE</label>
</div>
</div>
</form>
CSS
.selectthingy{
width: 300px;
}
.Box {
position: relative;
}
.Box select {
width: 100%;
}
.checkboxselect {
position: absolute;
right: 0;
left: 0;
bottom: 0;
top: 0;
}
#boxes_wrapper {
display: none;
border: 1px green solid;
}
#boxes_wrapper label {
display: block;
}
#boxes_wrapper label:hover {
background-color: blue;
}
JS
var boxthingy= false;
function showMeTheBoxes() {
var boxes = document.getElementById("boxes_wrapper");
if (!boxthingy) {
boxes.style.display = "block";
boxthingy= true;
} else {
boxes.style.display = "none";
boxthingy= false;
}
}
https://codepen.io/Archtects/pen/LmpLZr
Instead of the checkbox, I suggest to use a plain text with emoji. It will be show and hidden with an ngIf with the help of hasCheckbox property combined with a new property to keep the track of selected elements:
export class DropDownContent {
value: number;
text: string;
selected: boolean
}
...
this.contentInput = [{
"value": 0,
"text": "Users",
"selected": true
},
{...
So the template could be:
<select id="{{id}}" multiple>
<option (dblclick)="item.selected=!item.selected" *ngFor="let item of content; let i = index" value="{{item.value}}">
<span *ngIf="item.selected && hasCheckbox">✓</span>
{{item.text}}
</option>
</select>
Demo
Related
I want to show a spinner until the results load from the HTTP request on autocomplete field. Below is the snippet of the code written.
HTML
<label class="col-2 col-form-label text-right font-weight-bold">City *</label>
<div class="col-2">
<div>
<input id="typeahead-prevent-manual-entry" type="text" class="form-control"
[(ngModel)]="myActivity.city"
[ngbTypeahead]="search"
[inputFormatter]="formatter"
[resultFormatter]="formatter"
name="citySelected"
#citySelected="ngModel"/>
</div>
<div>
Typescript
formatter = (city: City) => city.name;
search = (text$: Observable<string>) => text$.pipe(
debounceTime(10),
distinctUntilChanged(),
filter(criterion => criterion.length >= 2),
map(criterion => criterion.length < 3 ? [] : this.searchLocalities(criterion).filter(city => new
RegExp(criterion, 'mi').test(city.name)).slice(0, 20))
);
searchLocalities(criterion: string): City[] {
this.isLoadingResult = true;
this.activityService.getLocalities(this.prvCodId, criterion).subscribe(
data => {
data.map(item => {
if (this.localities.find((city) => city.name === item.name) === undefined) {
this.localities.push(item);
}});
this.isLoadingResult = false;
});
return this.localities;
}
are you using material angular in your project? if yes you can easily use mat-proggress-spinner.
first of all import the module into your appModule:
import {MatProgressSpinnerModule} from '#angular/material/progress-spinner';
add it to your imports:
//
imports: [MatProgressSpinnerModule]
//
then in your template, you can use it as bellow:
<div class="col-2">
<mat-spinner *ngIf="isLoadingResult" diameter="30"></mat-spinner>
<div *ngIf="!isLoadingResult">
<input id="typeahead-prevent-manual-entry" type="text" class="form-control"
[(ngModel)]="myActivity.city"
[ngbTypeahead]="search"
[inputFormatter]="formatter"
[resultFormatter]="formatter"
name="citySelected"
#citySelected="ngModel"/>
</div>
<div>
but if you are not using material angular and you don't want to, you can just use a tag gif instead of mat-spinner.
put the gif in your assets and:
<img *ngIf="isLoadingResult" src="assets/images/loading.gif" />
in your html:
<div class="input-container">
<img class="loading-img" src="your loading img location">
<input type="text">
</div>
in your css:
.input-container {
display: flex;
position: relative;
width: 200px
}
.loading-img {
position: absolute;
right: 0;
top: 3px;
height: 20px;
width: 20px;
}
input {
width: 100%;
padding-right: 25px;
}
this will put the IMG in the right corner of the input.
You can use the mat-progress-bar library, see the example below.
//declaration
isApiCalling = false;
//use case
this.isApiCalling = true;
this._apiCall.get(this.url)
.subscribe(
data => {
this.isApiCalling = false;
},
err => {
this.isApiCalling = false;
}
);
<!-- actual term is isApiCalling -->
<mat-progress-bar mode="indeterminate" *ngIf="isApiCalling"></mat-progress-bar>
So am using a database to store data. and when i enter the data the [div class="col-md-3]
<div class="col-md-3" style="float: right; width: 500px">
<h2>Content from Firebase</h2>
<pre *ngFor=
"let item of items | async">{{item.content}}</pre>
</div>
stores the data but it doesn't reset when i relaunch the HTML. is there a way to reset this. am new to angular and node so not sure how i implement the function. even better if i can add the code straight to the HTML .
<div class="container-fluid" style="float: left">
<div style="color: blue;">
<h1>{{title}}</h1>
<h3>{{description}}</h3>
</div>
<div style="width: 300px;">
<form (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="ProductID">Item</label>
<input type="text" class="form-control"
placeholder="Enter content..." id="ProductID"
required [(ngModel)]="itemValue" name="Product">
</div>
<div class="form-group">
<label for="ingredients">Item</label>
<input type="text" class="form-control"
placeholder="Enter content..." id="ingredients"
required [(ngModel)]="itemValue2" name="ingredients">
</div>
<div class="form-group">
<label for="Price">Item</label>
<input type="number" class="form-control"
placeholder="Enter content..." id="Price"
required [(ngModel)]="itemValue3" name="Price">
</div>
<div class="form-group">
<label for="stock">Item</label>
<input type="number" class="form-control"
placeholder="Enter content..." id="stock"
required [(ngModel)]="itemValue4" name="stock">
</div>
<div class="form-group">
<label for="health Problems">Item</label>
<input type="text" class="form-control"
placeholder="Enter content..." id="health Problems"
required [(ngModel)]="itemValue5" name="health Problems">
</div>
<div class="btn-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
<div class="col-md-3" style="float: right; width: 500px">
<h2>Content from Firebase</h2>
<pre *ngFor="let item of items | async">{{item.content}}</pre>
</div>
import {Component, OnInit} from '#angular/core';
import { AngularFireDatabase } from '#angular/fire/database';
import { Observable } from 'rxjs';
import {FormControl, FormGroup, Validators} from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Angular8Firebase';
description = 'Angular-Fire-Demo';
//realtimedatabase
itemValue = '';
itemValue2 = '';
itemValue3 = '';
itemValue4 = '';
itemValue5 = '';
itemValue6 = '';
items: Observable<any[]>;
//storage database
imgSrc = '/assets/img/imgPlaceholder.jpg';
selectedImage: any = null;
isSubmitted = false;
//storage databaseormTemplate = new FormGroup({
caption : new FormControl('', Validators.required),
imageUrl : new FormControl('', Validators.required),
});
//realtimedatabase
constructor(public db: AngularFireDatabase) {
this.items = db.list('items').valueChanges();
}
//realtime database
onSubmit() {
this.db.list('items').push({ content: this.itemValue});
this.db.list('items').push({ content: this.itemValue2});
this.db.list('items').push({ content: this.itemValue3});
this.db.list('items').push({ content: this.itemValue4});
this.db.list('items').push({ content: this.itemValue5});
this.db.list('items').push({ content: this.itemValue6});
this.itemValue = '';
this.itemValue2 = '';
this.itemValue3 = '';
this.itemValue4 = '';
this.itemValue5 = '';
this.itemValue6 = '';
}
ngOnInit() {
}
//storage database
showPreview(event: any) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.onload = (e: any) => this.imgSrc = e.target.result;
reader.readAsDataURL(event.target.files[0]);
this.selectedImage = event.target.files[0];
} else {
this.imgSrc = '/assets/img/imgPlaceholder.jpg';
this.selectedImage = null;
}
}
//storage database
onSubmit2(formValue) {
this.isSubmitted = true;
if (this.formTemplate.value) {
const filePath = 'images/${this.selectedImage.name}_${new Date().getTime()}';
}
}
//storage database
get formControls() {
return this.formTemplate.controls;
}
}
I want to load a div section based on the status of the response from an api call,
I have a search box, on entering the value and click, if true is
returned then the div section is open
If false then the section remains close or should close.
APPROACH TRIED - defined a variable and using it as a condition at the div
section,
ISSUE - Works fine on the second click, but on the first click of the search never loads the section even if the value returned is true, instead on the second click works.
The below is the component code
export class EndorsementComponent implements OnInit{
fetch_endorse: any;
onSubmitPolNo() {
let formValueE: any = {
request_param : this.endorsSearchForm.value.searchViaPFEG,
}
this.endorsService.getEndorsePolicy(formValueE)
.pipe()
.subscribe(endorsearchdata => {
this.displayEndorseSearch(endorsearchdata),
console.log('endorsearchdata: ', endorsearchdata); //
(error: any) => this.errorMessage = <any>error
}
)
}
displayEndorseSearch(endorsearchdata): void {
this.endorsearchdata = endorsearchdata;
console.log('endorsearchdata: ', endorsearchdata); //
if (this.endorsearchdata.status == false) {
this.fetch_endorse = false;
const message = this.endorsSearchForm.value.searchViaPFEG + ` Does not exist.`;
this.layoutUtilsService.showActionNotification(message, MessageType.Update, 10000, true, false);
}
else {
this.fetch_endorse = true;
console.log(this.endorsearchdata.status)
}
And the below is the html
<div *ngIf ="fetch_endorse" class="m-portlet">
<form class="m-form m-form--fit m-form--group-seperator" novalidate [formGroup]="endorsForm" >
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon m--hide">
<i class="la la-gear"></i>
</span>
<h3 class="m-portlet__head-text">
Policy Detail
</h3>
</div>
</div>
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text w-100">
Endorsement Status:
</h3>
<mat-form-field class="no-line in-line example-full-width flex:1">
<h3>
<input matInput formControlName ="endr_status">
</h3>
</mat-form-field>
</div>
</div>
</div>
<div class="m-portlet__body">
<div class="m-form__section m-form__section--first">
<div class="form-group m-form__group row">
<label class="col-lg-1.5 col-form-label">Policy Number:</label>
<div class="col-lg-3">
<mat-form-field class="example-full-width">
<input matInput formControlName ="policy_number">
</mat-form-field>
</div>
<label class="col-lg-1.5 col-form-label">Insured Name:</label>
<div class="col-lg-3">
<mat-form-field class="example-full-width">
<input matInput formControlName ="insured_name">
</mat-form-field>
</div>
Via using the css to hide and show
added the following style to the css
::ng-deep .show {
opacity: 1;
transition: opacity 1s;
}
::ng-deep .hide {
opacity: 0;
transition: opacity 1s;
}
HTML - Gave an ID to my Div to refer it at the component
<div #myDiv class="m-portlet">
<form class="m-form m-form--fit m-form--group-seperator" novalidate [formGroup]="endorsForm" >
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon m--hide">
<i class="la la-gear"></i>
</span>
<h3 class="m-portlet__head-text">
Calculate Detail
</h3>
</div>
</div>
At the component added this condition
export class EndComponent implements OnInit {
public fetch_endorse: boolean = false;
#ViewChild("myDiv") myDiv;
ngOnInit() {
this.fetch_endorse = false;
this.myDiv.nativeElement.classList.add("hide");
this.myDiv.nativeElement.classList.remove("show");
}
functionTest(){
this.fetch_endorse = this.endorsearchdata.status;
if (!this.fetch_endorse) {
this.myDiv.nativeElement.classList.add("hide");
this.myDiv.nativeElement.classList.remove("show");
}
else {
//this.fetch_endorse = true;
this.myDiv.nativeElement.classList.add("show");
this.myDiv.nativeElement.classList.remove("hide");
}
}
}
So I am having a bit of a problem. I have to create a search page for a travel agency. In this example, I'm booking a flight. I have no idea how to display each result based off the inputs of the form ahhhhh. I've been trying but I ran outta mental energy for the day smh.
Here is some code:
HTML
<!-- Search Form -->
<form class="" action="index.html" method="post">
<h1> Let's Go. </h1>
<hr>
<select class="" name="">
<option value="">Select means of Travel</option>
<option value="">Flight</option>
</select>
<label for="Travel Start Date">Travel Start Date</label>
<input type="date" name="" value="Travel Start Date">
<label for="Travel End Date">Travel End Date</label>
<input type="date" name="" value="Travel End Date">
<select class="" name="">
<option value="">Departure Location</option>
<option value="Atlanta">Atlanta</option>
</select>
<select class="" name="">
<option value="">Arrival Location</option>
<option value="San Francisco">San Francisco</option>
</select>
<select class="" name="">
<option value="">Product Class</option>
<option value="">Economy</option>
</select>
<input style="width: 100px; background-color: green; color: #eef; height: 40px; border-radius: 50px; margin: 0 auto; margin-top: 50px;"
type="submit" name="" value="Submit" onclick="">
</form>
<!-- Results -->
<div class="result">
<ul>
<li *ngFor = 'let group of displayItems'>
<div class="flight-card">
<div class="availability">
<h5> Availability: {{group.availability}} </h5>
</div>
<div class="price">
{{ group.price.symbol }}
{{ group.price.amount }}
<p>{{ group.price.currency }}</p>
</div>
<div class="arrival">
<h5> Arrival City: </h5>{{group.arrival.city}} <br>
<h5> Arrival Airport Name: </h5>{{group.arrival.airport.name}} <br>
<h5> Arrival Time: </h5>{{group.arrival.city}} <br><br>
</div>
<hr>
<div class="depature">
<h5> Depature City: </h5>{{group.departure.city}} <br>
<h5> Departure Airport Name: </h5>{{group.departure.airport.name}} <br>
<h5> Departure Time: </h5>{{group.departure.time}} <br><br>
</div>
</div>
</li>
</ul>
</div>
(In root App)
Component.Ts
import { Component } from '#angular/core';
import { Http, Response, RequestMethod, RequestOptions, Headers } from '#angular/http';
import { NgIf } from '#angular/common';
import { Form } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
result;
errorFromSubscribe;
errorFromCatch;
displayItems;
// Inject HttpClient into your component or service.
constructor(private http: Http) {}
ngOnInit(): void {
// Making the HTTP Request
this.http
// Get API data
.get('https://api.myjson.com/bins/1gb9tf')
// Subscribe
.subscribe( (res: Response) => {
// Parses the response to JSON.
this.result = res.json();
this.displayItems = this.result['results'];
console.log(this.result);
}, error => {
console.log(error)
this.errorFromSubscribe = error;
});
}
title = 'app';
}
You need to use pipe for filtering by applying a specific logic to filter items for search
<li *ngFor="let group of displayItems | filter: term">
and the pipe as follows,
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any, term: any): any {
if (term === undefined) return items;
return items.filter(function(item) {
for(let property in item){
if (item[property] === null){
continue;
}
if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
return true;
}
}
return false;
});
}
}
DEMO
i have added angular routing to my crud operation.. before without routing the data i added was able to display in the table but now after implementation of routing the data is not getting stored in the table
here is the code of createemployee.component.html
<h2>Add Employee:</h2>
<form class="form-horizontal" #empForm="ngForm">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" minlength="4" maxlength="10" pattern="^[A-Za-z0-9]*[A-Za-z0-9][A-Za-z0-9]\S*$" [(ngModel)]="model.name" placeholder="Enter Your Name"
#name="ngModel" required/>
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.pattern">
No Spaces
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="position">Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="position" minlength="4" maxlength="10" pattern="^[a-z]*$" [(ngModel)]="model.position" placeholder="Enter your position"
#position="ngModel" required />
<div *ngIf="position.invalid && (position.dirty || position.touched)" class="alert alert-danger">
<div *ngIf="position.errors.required">
Position is required.
</div>
<div *ngIf="position.errors.pattern">
Only Alphabets are must be entered
</div>
<div *ngIf="position.errors.minlength">
Position must be at least 4 characters long.
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="salary">Salary:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="salary" pattern="[0-9]*"
minlength="5" maxlength="7" [(ngModel)]="model.salary" placeholder="Enter Salary" #salary="ngModel" required />
<div *ngIf="salary.invalid && (salary.dirty || salary.touched)" class="alert alert-danger">
<div *ngIf="salary.errors.required">
Salary is required.
</div>
<div *ngIf="salary.errors.minlength">
Salary must be in 5 numbers.
</div>
<div *ngIf="salary.errors.maxlength">
Salary must not be exceeded morethan 7 numbers.
</div>
<div *ngIf="salary.errors?.pattern">Only numebers should be typed
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" routerLink="../viewemployee" [disabled]="empForm.invalid">Add Employee</button>
<button type="button" class="btn btn-default" routerLink="../home">Cancel</button>
</div>
</div>
</form>
createemployee.component.ts
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup , Validators} from '#angular/forms';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#Component({
selector: 'app-createemployee',
templateUrl: './createemployee.component.html',
styleUrls: ['./createemployee.component.css']
})
export class CreateemployeeComponent implements OnInit {
model: any = {};
model2: any = {};
add=false;
create=true;
ngOnInit() {
this.model = new FormGroup({
'name': new FormControl(this.model.name,
[Validators.required, Validators.minLength(4),]),
'position': new FormControl(this.model.position,
[Validators.required, Validators.minLength(4),]),
'salary': new FormControl(this.model.salary, Validators.required)
});
}
employees = [{name: "Sunil", position: "Developer", salary: 20000},
{name: "Vamshi", position: "Java Developer", salary: 30000},
{name: "Chethan", position: ".Net Developer", salary: 10000}];
createEmp(){
this.add=true;
this.create=false;
this.Show=false;
this.edit=false;
}
addEmployee() {
this.employees.push(this.model);
this.Show = true;
this.add = false;
this.model = {};
}
}
viewemployeecomponent.ts
<h2>Employee Details</h2>
<table class="table table-bordered">
<thead>
<tr>
<th width=400>Name</th>
<th width=400>Position</th>
<th width=200>Salary</th>
<th width=400>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees; let i=index">
<td>{{employee.name}}</td>
<td>{{employee.position}}</td>
<td>{{employee.salary}}</td>
<td>
<a class="btn btn-success" (click)="editEmployee(i)">Edit</a>
<a class="btn btn-danger" (click)="deleteEmployee(i)">Delete</a>
</td>
</tr>
</tbody>
</table>
app.router.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { CreateemployeeComponent } from './createemployee/createemployee.component';
import { ViewemployeeComponent } from './viewemployee/viewemployee.component';
import { UpdateemployeeComponent } from './updateemployee/updateemployee.component';
export const router: Routes = [
{ path: '',redirectTo: 'home',pathMatch: 'full'},
{ path: 'createemployee', component: CreateemployeeComponent },
{ path: 'updateemployee', component: UpdateemployeeComponent},
{ path: 'viewemployee', component: ViewemployeeComponent },
{ path: 'home', component: HomeComponent},
{ path: 'appcomponent', component: AppComponent}
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router)
where did i have done the mistake.. i am trying to add the created employee into existing table with all other 3 hard coded employees
form what i ca see your problem is you're pushing a new employee in a component ..but you render the employee table in another and i see yours employee array is not from a service or from a #input() directive ...
so for example create a service like:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Rx';
import { environment } from '../../../../environments/environment';
import { PraticheGridVM, PraticheDTO } from 'app/awards/shared/models';
#Injectable()
export class EmployeeService {
private employees = [{name: "Sunil", position: "Developer", salary: 20000},
{name: "Vamshi", position: "Java Developer", salary: 30000},
{name: "Chethan", position: ".Net Developer", salary: 10000}];
constructor(private http: HttpClient) { }
/**
* Get Pratiche Mese Paginate
* #param {PraticheGridVM} filter
* #returns {Promise<Array<PraticheDTO>>}
* #memberof PraticheService
*/
public GetEmployee(): Array<Employee> {
return this.employees;
}
/**
* Get Pratiche Trimestre Paginate
* #param {PraticheGridVM} filter
* #returns {Promise<PraticheDTO>}
* #memberof PraticheService
*/
public AddEmployee(emp: Employee): Array<Employee> {
return this.employees.push(emp);
}
}
and then use it in your components .. like:
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup , Validators} from '#angular/forms';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import {EmployeeService} from 'yourservicePATH'
#Component({
selector: 'app-createemployee',
templateUrl: './createemployee.component.html',
styleUrls: ['./createemployee.component.css']
})
export class CreateemployeeComponent implements OnInit {
model: any = {};
model2: any = {};
add=false;
create=true;
constructor(private employeeService: EmployeeService){
}
ngOnInit() {
this.model = new FormGroup({
'name': new FormControl(this.model.name,
[Validators.required, Validators.minLength(4),]),
'position': new FormControl(this.model.position,
[Validators.required, Validators.minLength(4),]),
'salary': new FormControl(this.model.salary, Validators.required)
});
}
employees = [{name: "Sunil", position: "Developer", salary: 20000},
{name: "Vamshi", position: "Java Developer", salary: 30000},
{name: "Chethan", position: ".Net Developer", salary: 10000}];
createEmp(){
this.add=true;
this.create=false;
this.Show=false;
this.edit=false;
}
addEmployee() {
this.employeeService.AddEmployee(this.model);
this.Show = true;
this.add = false;
this.model = {};
}
}