This is my code so far:
My component.html:
<div class="container">
<Form #a ="ngForm" ngForm (ngSubmit)="onSubmit(a)">
<div *ngFor="let question of questions">
<div class = "form-group">
<a>{{question.questionId}}. {{question.question}}</a><br>
<input type="radio" ngModel name="Ans{{question.questionId}}" value="A" >
<label for="html">A. {{question.optionsA}}</label><br>
<input type="radio" ngModel name="Ans{{question.questionId}}" value="B" >
<label for="html">B. {{question.optionsB}}</label><br>
<input type="radio" ngModel name="Ans{{question.questionId}}" value="C" >
<label for="html">C. {{question.optionsC}}</label><br>
<input type="radio" ngModel name="Ans{{question.questionId}}" value="D" >
<label for="html">D. {{question.optionsD}}</label><br>
</div>
</div>
<button class="btn btn-primary " type="submit" >Submit</button>
</Form>
<div *ngIf="results.length >0">
<table>
<thead>
<th>Question No.</th>
<th>Correct Answer</th>
<th>Your Answer</th>
</thead>
<tbody *ngFor="let question of questions">
<td>{{question.questionId}}</td>
<td>{{question.answer}}</td>
</tbody>
</table>
{{score}}
{{results.length}}
</div>
</div>
and my component.ts:
import { Component, OnInit } from '#angular/core';
import { Quiz1 } from 'src/app/models/quiz1.model';
import { Quiz1Service } from 'src/app/services/quiz1.service';
import {FormControl, FormGroup, NgForm} from '#angular/forms';
#Component({
selector: 'app-quiz1',
templateUrl: './quiz1.component.html',
styleUrls: ['./quiz1.component.css']
})
export class Quiz1Component implements OnInit {
questions?: Quiz1[];
currentQuestion: Quiz1 = {};
currentIndex = -1;
score = 0;
results:String[] = [];
//index?: String[] = ['Ans1','Ans2'];
constructor(private quiz1Service: Quiz1Service) { }
ngOnInit(): void {
this.retrieveQuestions();
}
retrieveQuestions(): void {
this.quiz1Service.getAll()
.subscribe({
next: (data: any) => {
this.questions = data;
console.log(data);
},
error: (e: any) => console.error(e)
});
}
onSubmit(a:NgForm){
this.results?.push(a.value);
console.log(this.results);
console.log(this.results.length)
this.questions?.forEach((questions) => {
console.log(questions.questionId);
if(questions.answer==this.results[questions.questionId-1]){
this.score++
console.log(this.score)
}
});
}
}
When I print the results array in the console, this is what I got:
Array(1)
0: {Ans1: 'A', Ans2: 'C'}
length: 1
[[Prototype]]: Array(0)
as you can see, it is storing all the data in a single index and with the field name which won't do at all.
What I want is just the field data stored in different index in the array so I can use that.
Is that possible?
I don't think you can achieve what you want using template-driven forms.
You would have to use reactive forms and FormArray.
Related
I am currently developing an angular application with a django backend, I use ngModel to retrieve lists in selects which allow me to filter a list of checkboxes, however I want to insert in my Reactiveforms the identifier of the selected gears, and i have conflicts between some ngmodels and my Reactiveform doesn't quite understand why And when i add the formArrayName i don't have my select list anymore either, i wonder if it's also a conflict with ngmodel do you have any thoughts on this?
I however used the method [ngModelOptions]="{standalone: true}"
[console error][1]
[1]: https://i.stack.imgur.com/FtQAw.png
HTML
<form [formGroup]="form" (ngSubmit)="submitForm()">
<label for="name">Nom de la flotte à créer</label>
<input class="Nflotte" formControlName="name" type="text" #flotteName placeholder="Nom de la flotte" required>
<div class="wrapper">
<div class="one">
<wcs-select [(ngModel)]="SelectedSerie" name="SelectedSerie" [ngModelOptions]="{standalone: true}" placeholder="Série" id="leselectg" (ngModelChange)="getEnginBySeries()">
<wcs-select-option *ngFor="let serie of series" [value]="serie">{{
serie.code_serie_materiel }}</wcs-select-option>
</wcs-select>
<wcs-select [(ngModel)]="SelectedSousSerie" [ngModelOptions]="{standalone: true}" placeholder="Sous-série" id="leselectg" (ngModelChange)="getEnginBySousSeries()">
<wcs-select-option *ngFor="let sousSerie of SelectedSerie?.sousseries" [value]="sousSerie">{{
sousSerie.code_serie_materiel }}</wcs-select-option>
</wcs-select>
<wcs-select [(ngModel)]="SelectedVariante" [ngModelOptions]="{standalone: true}" placeholder="Variantes" id="leselectg" (ngModelChange)="getEnginByVariante()">
<wcs-select-option *ngFor="let variante of SelectedSousSerie?.variantes">
{{ variante.code_serie_materiel }}
</wcs-select-option>
</wcs-select>
</div>
<div class="two">
</div>
<div class="three">
</div>
</div>
<div class="wrapper">
<div class="fsearch one">
<div class="wrap">
<div class="search">
<input type="text" class="searchTerm" id="search-text" aria-describedby="search-text"
[(ngModel)]="searchText" placeholder="Rechercher un engin" [value]="">
<button type="submit" class="searchButton">
<i class="material-icons">search</i>
</button>
</div>
</div>
</div>
<div class="two"></div>
<div class=" three">
</div>
</div>
<div class="wrapper">
<div class="one">
<form novalidate>
<table class="blueTable" formArrayName="engins">
<thead>
<tr>
<th>Sélectionner tout les engins</th>
<th >num_facade</th>
<th >num_immatriculation_ef</th>
</tr>
</thead>
<tbody style="margin: 15px;" >
<input type="checkbox" [(ngModel)]="masterSelected" [ngModelOptions]="{standalone: true}" name="list_name" value="m1"
(change)="checkUncheckAll()"/>
<tr class="list-group" [formControlName]="i" style="list-style-type: none;" *ngFor="let engin of form.controls?.engins?.controls | appFilter: searchText; let i = index" >
<input type="checkbox" [(ngModel)]="engin.isSelected" name="list_engins[]" formControlName="checked" value="{{engin[i].identifiant}}"
(change)="isAllSelected()"/>
<td>{{engin.num_facade}}</td>
<td>{{engin.num_immatriculation_ef}}</td>
</tr>
</tbody>
</table>
</form>
</div>
</form>
Component.ts
import { Component, OnInit, Input, Pipe, PipeTransform } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { FlotteService } from 'src/app/services/flotte.service';
import { ApiService } from 'src/app/services/api.service';
import { Engins, SerieBase, SousSerieEngin, VariantesEngin } from 'src/app/interface/serie';
import { SerieEngin } from 'src/app/interface/serie';
import { Flotte } from 'src/app/interface/flotte';
import { VisualisationComponent } from '../visualisation/visualisation.component';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Emitters } from 'src/app/emitters/emitters';
import { NgForm } from '#angular/forms';
import { FormBuilder } from '#angular/forms';
import { FormGroup, Validators, FormControl, FormArray } from '#angular/forms';
export class FlotteComponent implements OnInit {
message: any;
error: any;
SelectedSerie?: SerieEngin;
SelectedSousSerie?: SousSerieEngin;
SelectedVariante?: VariantesEngin;
SelectedFlotte?: Flotte;
SelectionSerie: String = '';
ngOnInit(): void {
this.http.get('http://localhost:8000/api/user', {withCredentials: true}).subscribe(
(res: any) => {
this.message = `Bonjour ${res.username}`;
Emitters.authEmitter.emit(true);
},
);
this.getAllFlottes()
this.flotteservice.getSeries2()
.subscribe(response => {
this.series = response;
}
)
this.engins.forEach(engin => {
if (engin.value) {
engin.value.forEach((checkbox: any) => {
})
}
})
this.engins = [];
this.form = new FormGroup({
// control for radio exemple
name: new FormControl(null, Validators.required),
// control for Checkbox exemple
engins: new FormArray([]),
calculateur: new FormControl(null, Validators.required),
type_fichier: new FormControl(null, Validators.required),
});
// bind existing value to form control
this._patchValues();
}
private _patchValues(): void {
// get array control
const formArray = this.form.get('engins') as FormArray;
// loop for each existing value
this.engins.forEach((engin) => {
// add new control to FormArray
formArray.push(
// here the new FormControl with item value from RADIO_LIST_FROM_DATABASE
new FormGroup({
fengins: new FormControl(engin.identifiant),
checked: new FormControl(engin.checked),
})
);
});
}
submitForm(): void {
const { value } = this.form;
// get selected fruit from FormGroup value
const selectedEngin =
value?.engins?.filter((f: Engins) => f.checked) || [];
// form value binded
console.log('current form value: ', value);
console.log('only selected form value: ', selectedEngin);
// original value from database not change
console.log('original engins list: ', this.engins);
this.result = {
name: value?.name || '',
selectedEngin,
calculateur: value?.calculateur || '',
type_fichier: value?.type_fichier|| '',
}
this.api.registerFlotte(this.form.value)
.subscribe((res:any)=>{console.log(res)});
}
}
I have an array of inputs:
<div id="playerZone" *ngFor="let player of team;let i=index">
<div id="buttonZone">
<div class="buttonsAdd">
<mat-form-field appearance="outline" #f="ngForm">
<mat-label>Summoner Name</mat-label>
<label>
<input matInput placeholder="Placeholder"
(change)="updatePlayerSumonerName($event,i)">
</label>
</mat-form-field>
</div>
</div>
<button mat-raised-button routerLink="/waiting" [disabled]="" (click)="placeOnTheList()" hidden="">Waiting Room</button>
And a button that i only want to enable if all inputs are filled, and i dont know how to do that.
I need some guidance.
I could create variables that get to true when the input is written, but i know that is a better way of do that
updatePlayerSumonerName(name,i){
console.log(name.target.value);
this.team[i].summonerName = name.target.value;
}
You can achieve ur requirement as below.
Please check this Demo
in your app.component.ts,
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, FormArray, Validators, FormBuilder } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
players = [
'player1',
'player2',
'player3',
'player4'
];
constructor(private fb: FormBuilder) { }
form = this.fb.group({
team: new FormArray([])
});
ngOnInit() {
this.addPlayers(this.players);
}
get team(): FormArray {
return this.form.get('team') as FormArray;
}
onFormSubmit(): void {
for (let i = 0; i < this.team.length; i++) {
console.log(this.team.at(i).value);
}
}
addPlayers(players: string[]): void {
players.forEach(player => {
this.team.push(new FormControl(player, [Validators.required]));
});
}
}
and app.component.html,
<div class="container">
<br>
<form [formGroup]="form" (ngSubmit)="onFormSubmit()">
<div formArrayName="team">
<div class="form-group row">
<label for="commessa" class="col-sm-2 col-form-label">Team</label>
<div class="col-sm-10">
<ng-container *ngFor="let player of team.controls; index as idx">
<div class="row">
<div class="col-sm-8">
<input type="text" [ngClass]="{'error':player.invalid && player.touched}"
[formControlName]="idx" class="form-control" id="commessa">
</div>
</div>
</ng-container>
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary" [disabled]="form.invalid">Save</button>
</div>
</form>
</div>
I am doing a project that is able to let user fill in student details and the is an Edit button which will display the student details into the input area.
There are two routerlink in my project = Add student , Student List.
I want the project redirect to Add student page when I click Edit button in Student List but I cannot do that.
The project folder in Github
app.module.html
<html><h1>{{title}}</h1>
<nav>
<a class="link" routerLink="/write" routerLinkActive="active">Add Student</a>
<a class="link" routerLink="/read" routerLinkActive="active">Student List</a>
</nav>
<router-outlet></router-outlet>
</html>
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { WriteComponent } from './write/write.component'
import { ReadComponent } from './read/read.component';
const routes: Routes = [
{path:"write",component:WriteComponent},
{path:"read",component:ReadComponent},
{path:'index',component:ReadComponent}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents = [ WriteComponent,ReadComponent]
read.component.html //Student List page
<div class="user-list" *ngIf="usersList && usersList.length" >
<h2>List of Student</h2>
<table class="table table-condensed">
<thead>
<tr>
<th>SL.No</th>
<th>Name</th>
<th>Age</th>
<th>College</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of usersList; let i = index" >
<th>{{i}}</th>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td>{{user.college}}</td>
<td>
<button style="margin-right: 5px;" class="btn-warning" (click)="onSelect(i)" (click)="editStudent(i)">Edit</button>
<a [routerLink]="['/write']"></a>
<button class="btn-danger" (click)="deleteStudent(i)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
read.component.ts
import { Component, OnInit } from '#angular/core';
import { Student } from '../student';
import { ActivatedRoute , Router, ParamMap} from '#angular/router';
#Component({
selector: 'app-read',
templateUrl: './read.component.html',
styleUrls: ['./read.component.css']
})
export class ReadComponent implements OnInit {
public index;
constructor(private route : ActivatedRoute, private router : Router) { }
user: User;
usersList: User[] = [
{name:"Johnny",age:'22',college:"INTI"},
{name:"Samantha",age:'26',college:"Harvard"},
{name:"Zoe",age:'21',college:"TARUC"},
{name:"Chris",age:'25',college:"Sunway"},
]
ngOnInit(): void {
this.resetForm();
this.route.paramMap.subscribe((params:ParamMap) => {
let Index = parseInt(this.route.snapshot.paramMap.get('index'));
this.index = Index;
});
}
editStudent(index: number) {
this.user = this.usersList[index];
this.deleteStudent(index);
}
deleteStudent(index: number) {
this.usersList.splice(index, 1);
}
resetForm() {
this.user = {age: null, name: '', college: ''};
}
onSelect(index : number){
this.router.navigate(['/user',index])
}
}
interface User {
name: string;
age: string;
college: string;
}
write.component.html //add student page,since the list is the same I will not post again in here else there are too many code
<div class="container">
<h2>Add Student</h2>
<form class="form-inline" autocomplete="off" (submit)="addStudent()">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name" name="name" [(ngModel)]="user.name" >
</div>
<div class="form-group">
<label for="pwd">Age:</label>
<input type="number" class="form-control" id="age" name="age" [(ngModel)]="user.age">
</div>
<div class="form-group">
<label for="pwd">College:</label>
<input type="text" class="form-control" id="college" name="college" [(ngModel)]="user.college">
</div>
<button type="submit" class="btn-success">Submit</button>
</form>
write.component.ts
ngOnInit(): void {
this.resetForm();
}
addStudent() {
this.usersList.push(this.user);
this.resetForm();
}
resetForm() {
this.user = {age: null, name: '', college: ''};
}
// read.component.html
<button style="margin-right: 5px;" class="btn-warning" (click)="editStudent(i)">Edit</button>
// read.component.ts
editStudent(index: number) {
this.user = this.usersList[index];
this.deleteStudent(index);
this.router.navigateByUrl('/write');
}
In read.component.html file <a [routerLink]="['/write']"></a> will not work because you have not added any text in it so it will not display in the web so instead of, you can do in
editStudent(index: number) {
this.user = this.usersList[index];
this.deleteStudent(index);
this.router.navigate(['/write']);
}
I've created the nested FormGroup (questionnaire) which contains a FormArray (section) which contains another FormGroup (creatSection()) that contains another FormArray (question) in which we have another formgroup (creatQuestion()) in which we have another formarray(answer) that has a formgroup (creatAnswer())
Everything appears fine unless I want to add another question or another answer nothing the addSection works fine
so the creation is ok but the problem in the add.
what I'm thinking about is when you create a question it doesn't know to where it's going to be put in but I couldn't figure out how to fix it
my questionnaire.ts looks like this
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormArray } from '#angular/forms'
#Component({
selector: 'app-questionnaire',
templateUrl: './questionnaire.component.html',
styleUrls: ['./questionnaire.component.css']
})
export class QuestionnaireComponent implements OnInit {
questionnaire:FormGroup;
section:FormArray;
question:FormArray;
answer:FormArray;
constructor(private fb:FormBuilder) { }
ngOnInit() {
this.questionnaire=this.fb.group({
questionnaireName: [''],
section : this.fb.array([this.creatSection()])
})
}
creatSection():FormGroup{
return this.fb.group({
sectionName:[''],
question:this.fb.array([this.creatQuestion()])
})
}
addSection(){
this.section=this.questionnaire.get('section') as FormArray;
this.section.push(this.creatSection());
}
creatQuestion():FormGroup{
return this.fb.group({
questionName:[''],
type:[''],
answer:this.fb.array([this.creatAnswer()])
})
}
addQuestion(){
this.question=this.creatSection().get('question') as FormArray;
this.question.push(this.creatQuestion());
}
creatAnswer():FormGroup{
return this.fb.group({
id:[''],
answerName:['']
})
}
addAnswer(){
this.answer=this.creatQuestion().get('answer') as FormArray;
this.answer.push(this.creatAnswer());
}
onSubmit(){
console.log(this.questionnaire.value);
}
}
and the questionnaire.html is like this
<h1>questionnaire bla bla</h1>
<!-- <app-section></app-section> -->
<form [formGroup]="questionnaire" (ngSubmit)="onSubmit()">
<input type="text" placeholder="questionnaire..." formControlName="questionnaireName">
<ng-container formArrayName="section">
<div [formGroupName]="i" *ngFor="let ques of questionnaire.get('section').controls;let i = index;">
<input placeholder="section..." formControlName="sectionName" type="text">
<button (click)="addSection()">add section</button>
<ng-container formArrayName="question">
<div [formGroupName]="j" *ngFor="let sec of creatSection().get('question').controls;let j=index;">
<input placeholder="question..." formControlName="questionName" type="text">
<input placeholder="type..." formControlName="type" type="text">
<button (click)="addQuestion()">add question</button>
<ng-container formArrayName="answer">
<div [formGroupName]="k" *ngFor="let ans of creatQuestion().get('answer').controls;let k=index;">
<input placeholder="réponse..." formControlName ="answerName" type="text">
<button (click)="addAnswer()">add answer</button>
</div>
</ng-container>
</div>
</ng-container>
</div>
</ng-container>
<button type="submit">submit</button>
</form>
{{questionnaire.value | json}}
First Don't call to creatSection() in the .html
//WRONG
<div [formGroupName]="j" *ngFor="let sec of creatSection().get('question').controls;let j=index;">
//OK
<div [formGroupName]="j" *ngFor="let sec of ques.get('question').controls;let j=index;">
Well you need pass as argument the "indexs" of the arrays (I called "clasic way"), but you can also pass the group of the array itself
<button (click)="addAnswer(i,j)">add answer</button>
//or
<button (click)="addAnswer(sec)">add answer</button>
In a "clasic"
addAnswer(i:number:j:number)
{
const arraySection=((this.questionnaire.get('section') as FormArray)
const groupQuestion=(arraySection.get('question') as FormArray).at(i)
const arrayAnswer=groupQuestion.get('answer') as FormArray
arrayAnswer.push(this.creatAnswer())
}
If you pass the array itself
addAnswer(groupQuestion:FormArray)
{
const arrayAnswer=groupQuestion.get('answer') as FormArray
arrayAnswer.push(this.creatAnswer())
}
NOTE: with a stackblitz was easer check and it's possible eror in my code, please get it the idea
thanks to #Eliseo the result would look like
questionnaire.html
<h1>questionnaire bla bla</h1>
<form [formGroup]="questionnaire" (ngSubmit)="onSubmit()">
<input type="text" placeholder="questionnaire..." formControlName="questionnaireName">
<ng-container formArrayName="section">
<div [formGroupName]="i" *ngFor="let ques of questionnaire.get('section').controls;let i = index;">
<input placeholder="section..." formControlName="sectionName" type="text">
<button (click)="addSection()">add section</button>
<ng-container formArrayName="question">
<div [formGroupName]="j" *ngFor="let sec of ques.get('question').controls;let j=index;">
<input placeholder="question..." formControlName="questionName" type="text">
<input placeholder="type..." formControlName="type" type="text">
<button (click)="addQuestion(ques)">add question</button>
<ng-container formArrayName="answer">
<div [formGroupName]="k" *ngFor="let ans of sec.get('answer').controls;let k=index;">
<input placeholder="réponse..." formControlName ="answerName" type="text">
<button (click)="addAnswer(sec)">add answer</button>
</div>
</ng-container>
</div>
</ng-container>
</div>
</ng-container>
<button type="submit">submit</button>
</form>
{{questionnaire.value | json}}
and questionnaire.ts would look like this
import { Component,OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormArray } from '#angular/forms'
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
questionnaire:FormGroup;
section:FormArray;
question:FormArray;
answer:FormArray;
constructor(private fb:FormBuilder) { }
ngOnInit() {
this.questionnaire=this.fb.group({
questionnaireName: [''],
section : this.fb.array([this.creatSection()])
})
}
creatSection():FormGroup{
return this.fb.group({
sectionName:[''],
question:this.fb.array([this.creatQuestion()])
})
}
addSection(){
this.section=this.questionnaire.get('section') as FormArray;
this.section.push(this.creatSection());
}
creatQuestion():FormGroup{
return this.fb.group({
questionName:[''],
type:[''],
answer:this.fb.array([this.creatAnswer()])
})
}
addQuestion(groupSection:FormArray){
const arrayQuestion=groupSection.get('question') as FormArray
arrayQuestion.push(this.creatQuestion())
}
creatAnswer():FormGroup{
return this.fb.group({
id:[''],
answerName:['']
})
}
addAnswer(groupQuestion:FormArray){
const arrayAnswer=groupQuestion.get('answer') as FormArray
arrayAnswer.push(this.creatAnswer())
}
onSubmit(){
console.log(this.questionnaire.value);
}
}
1.After the data being entered , onClick of the submit button in nav.template.html.
2.FORM data should be passed into product.component.ts, Also the same data should be inserted inside the table in product.template.html.
3.In interface data types are being defined and passed through a service called product.data.js.
nav.component.ts
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
#Component({
moduleId: module.id,
selector: 'ng-nav',
inputs: ['products'],
templateUrl: 'nav.template.html'
})
export class NavbarComponent {
productForm: boolean=false;
isNewForm: boolean;
rForm : FormGroup;
post : any;
fname : string = '';
lname : string = '';
email : string = '';
phnum : number;
address : string = '';
ZipCode : number;
state : string = '';
country : string = '';
fnameAlert : string = 'Maximum 10 characters';
lnameAlert : string = 'Maximum 10 characters';
emailAlert : string = 'Maximum 50 characters in e-mail format';
phnumAlert : string = 'Maximum 10 digits';
addressAlert : string = 'Maximum 100 characters';
ZipCodeAlert : string = 'Maximum 10 characters';
constructor(private fb:FormBuilder){
this.rForm = fb.group({
'fname':[null,Validators.compose([Validators.required,Validators.maxLength(10),Validators.minLength(3)])],
'lname':[null,Validators.compose([Validators.required,Validators.maxLength(10),Validators.minLength(3)])],
'email':[null,Validators.compose([Validators.required,Validators.maxLength(50)])],
'phnum':[null,Validators.compose([Validators.required,Validators.maxLength(10)])],
'address':[null,Validators.compose([Validators.required,Validators.maxLength(10)])],
'ZipCode':[null,Validators.compose([Validators.required,Validators.maxLength(6)])],
'state':[null,Validators.required],
'country':[null,Validators.required],
'validate' : ''
});
}
addpost(post){
this.fname = post.fname;
this.lname = post.lname;
this.email = post.email;
this.phnum = post.phnum;
this.address = post.address;
this.ZipCode = post.ZipCode;
}
// saveProduct(product: Product){
// }
}
nav.template.html
<button (click)="showAddProductForm()"><i class="fa fa-plus add-plus-button"></i></button>
<div class="container">
<form [formGroup]="rForm" (ngSubmit)="addPost(rForm.value)" *ngIf="productForm">
<div class="form-container">
<div class="form-style-1">
<h2>Customer Details</h2>
<label>First Name<span class="required">*</span><input class="fname-holder" [(ngModel)]="newProduct.fname" type="text" formControlName="fname"/></label>
<div class="alert" *ngIf="!rForm.controls['fname'].valid && rForm.controls['fname'].touched">{{fnameAlert}}</div>
<label>Last Name<span class="required">*</span><input class="lname-holder" [(ngModel)]="newProduct.lname" type="text" formControlName="lname"/></label>
<div class="alert" *ngIf="!rForm.controls['lname'].valid && rForm.controls['lname'].touched">{{lnameAlert}}</div>
<label>Email <span class="required">*</span><input type="email" [(ngModel)]="newProduct.email" formControlName="email"/></label>
<div class="alert" *ngIf="!rForm.controls['email'].valid && rForm.controls['email'].touched">{{emailAlert}}</div>
<label>Phone <span class="required">*</span><input type="text" [(ngModel)]="newProduct.phnum" formControlName="phnum"/></label>
<div class="alert" *ngIf="!rForm.controls['phnum'].valid && rForm.controls['phnum'].touched">{{phnumAlert}}</div>
<label>Address <span class="required">*</span><textarea style="width: 319px;"type="address" [(ngModel)]="newProduct.id" formControlName="address"></textarea></label>
<div class="alert" *ngIf="!rForm.controls['address'].valid && rForm.controls['address'].touched">{{addressAlert}}</div>
<label>Zip Code <span class="required">*</span><input type="text" [(ngModel)]="newProduct.ZipCode" formControlName="ZipCode"/></label>
<div class="alert" *ngIf="!rForm.controls['ZipCode'].valid && rForm.controls['ZipCode'].touched">{{ZipCodeAlert}}</div>
<label>State <span class="required">*</span><input type="text" [(ngModel)]="newProduct.state" formControlName="state"/></label>
<label>Country <span class="required">*</span><input type="text" [(ngModel)]="newProduct.country" formControlName="country"/></label>
<input type="submit" style="width: 95px;" class="button button2" value="Submit" (click)="saveProduct(newProduct)" [disabled]="!rForm.valid"/>
</div>
</div>
</form>
</div>
product.component.ts
import { Component, OnInit } from '#angular/core';
import { Product} from './product';
import { ProductService } from './product.service';
#Component({
moduleId: module.id,
selector: 'ng-product',
templateUrl: 'product.template.html'
})
export class ProductComponent implements OnInit{
products:Product[];
productForm:boolean = false;
isNewForm:boolean;
constructor (private _productService:ProductService){}
ngOnInit(){
this.getProducts();
}
getProducts(){
this.products = this._productService.getProductsFromData();
}
removeProductForm(product: Product){
this._productService.deleteProduct(product);
}
}
product.template.html
<div>
<div>
<div style="float: right;"><input class="filter-search" placeholder="Search..." type="text" [(ngModel)]="term">
<i class="fa fa-search search-bar-icon"></i>
</div>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
<th>Address</th>
<th>Zipcode</th>
<th>State</th>
<th>Country</th>
<th></th>
<th></th>
</tr>
<tr *ngFor="let product of products|filter:term">
<td>{{product.fname}}</td>
<td>{{product.lname}}</td>
<td>{{product.email}}</td>
<td>{{product.phnum}}</td>
<td>{{product.address}}</td>
<td>{{product.ZipCode}}</td>
<td>{{product.state}}</td>
<td>{{product.country}}</td>
<td><i class="fa fa-edit" style="font-size:24px;color: #3eb0f7;" (click)="showEditProductForm(product)"></i></td>
<td><i class="fa fa-trash" style="font-size:24px;color: #ff3232;" (click)="removeProductForm(product)"></i></td>
</tr>
</table>
</div>
</div>
<ng-nav [products]="products"></ng-nav>
product.service.ts
import{Injectable} from '#angular/core';
import{Product} from './product';
import{PRODUCT_ITEMS} from './product.data';
#Injectable()
export class ProductService {
private pItems = PRODUCT_ITEMS;
getProductsFromData():Product[]{
console.log(this.pItems);
return this.pItems
}
deleteProduct(product: Product){
this.pItems.splice(this.pItems.indexOf(product),1)
}
}
You can use Subject or BehaviourSubject from rxjs. Pass the submitted data to next method of Observable and subscribe it to another component and you will get the data there.
Your newProduct should exists in product.component.ts. By the magic of two way data binding you have the data in the component.
To send it to the service..
export class ProductComponent implements OnInit{
products:Product[];
newProduct: Product;
constructor (private _productService:ProductService){}
ngOnInit(){
this.getProducts();
}
onSubmit(){
this._productService.addProduct(this.newProduct);
}