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);
}
Related
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.
I am trying for 3 day and looking for a solution in to fix this problem but I am not success. I have read a problem with the same title but it did not help me in solving because it is different from my problem.
I hope that someone can help me .
Problem Description :
I have a Modal which send from one component to another component , this Modal should allow the user to Update the Student Information after calling the Method onUpdate() .
so I have Component A and Child A and the exchange some Data by using service file .
Component A has the Method onUpdate (userData) --> send to service --> Child A
javaScriptCode for Component A
onUpdate(userId: number, index: number) {
this.isOnDeleteORUpdate = true;
**// here the data will be fetched from DB and send to the Service,
// so that can be shown in Modal Form**
if (this.isOnDeleteORUpdate) {
this.requestService.getUserWithId(userId).subscribe((userData) => {
this.theModalServiceUpdate.setUser(userData);
this.theModalServiceUpdate.setUser(userData);
if (userData.courses.length <= 0 || userData.courses == null) {
this.loadedCourses = [];
this.theModalService.setCourses([]);
} else {
this.loadedCourses = userData.courses;
this.theModalService.setCourses(userData.courses);
}
});
this.modalService
.open(this.theModalServiceUpdate.modalTemplate, { centered: true })
.result.then(
(res) => {
this.closeModal = `Closed with: ${res}`;
},
(res) => {
this.closeModal = `Dismissed ${this.getDismissReason(res)}`;
}
);
}
}
Modal HTML Code:
<ng-template #modalData let-modal>
<div class="modal-dialog-scrollable modal-dialog-centered" id="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-basic-title">Modal title</h5>
<button
type="button"
class="btn-close"
data-dismiss="modal"
aria-label="Close"
(click)="modal.dismiss('Cross click')"
></button>
</div>
<div class="modal-body">
<form [formGroup]="userForm">
<label for="firstName">First Name</label>
<input
type="text"
class="form-control"
name="firstName"
formControlName="firstName"
/>
<label for="lastName">Last Name</label>
<input
type="text"
class="form-control"
name="lastName"
formControlName="lastName"
/>
<label for="email">Email</label>
<input
type="email"
class="form-control"
name="email"
formControlName="email"
/>
<label for="address">Address</label>
<input
type="text"
class="form-control"
name="address"
formControlName="address"
/>
<label for="telNumber">Telfone no.</label>
<input
type="text"
class="form-control"
name="telNumber"
formControlName="telNumber"
/>
<label for="gebDatum">gebDatum</label>
<input
type="text"
class="form-control"
name="gebDatum"
formControlName="gebDatum"
/>
</form>
<div class="card-body">
<div
style="
border-radius: 6px;
overflow: hidden;
border: 0.05em solid rgb(218, 231, 198);
"
>
<table class="table table-hover table-responsive">
<thead style="background-color: gray; text-align: center">
<tr>
<th scope="col">Id</th>
<th scope="col">Course Name</th>
<th scope="col">Serial Number</th>
</tr>
</thead>
<tbody>
<tr
*ngFor="let course of loadedCourses"
style="text-align: center"
>
<td>{{ course.id }}</td>
<td>
<input type="text" [value]="course.name" />
</td>
<td>
<input type="text" [value]="course.serialNumber" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button (click)="saveData()" type="button" class="btn btn-danger">
Close
</button>
</div>
</div>
</div>
</ng-template>
its work for me fine and the Student Data are fetched from DataBase in the Input fields .
but I can't inter Any Information , the Input Field is frozen only I can inter the Courses Information because I user the [value] data binding in HTML instead of ngForm.
see photo: as you can see the Modal divided in tow section , in the upper one I get the data from DB but I can't modify it. in the Table Section because I am using the data binding and not the ngForm so I can enter information .
The code in JavaScript look like the following :
import { Component, OnInit, TemplateRef, ViewChild } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { courses } from 'src/app/userInfo/courses.module';
import { userInfo } from 'src/app/userInfo/user.module';
import { modalServiceUpdate } from '../../modal.updateUser.service';
#Component({
selector: 'app-modal-update-student',
templateUrl: './modal-update-student.component.html',
styleUrls: ['./modal-update-student.component.css'],
})
export class ModalUpdateStudentComponent implements OnInit {
#ViewChild('modalData') templateRef: TemplateRef<any>;
userForm: FormGroup;
loadedUser: userInfo;
lodedUserId: number = 0;
loadedCourses: courses[] = [
{
id: 0,
name: 'undefine',
serialNumber: 0,
},
];
user: userInfo = {
id: 0,
firstName: 'undefined',
lastName: 'undefined',
email: '',
gebDatum: 0,
telNumber: 0,
address: '',
courses: [],
};
constructor(private modalServiceUpdate: modalServiceUpdate) {}
loadedUserFromService: userInfo;
ngOnInit(): void {}
ngDoCheck(): void {
this.initForm();
}
private initForm() {
this.modalServiceUpdate.modalTemplate = this.templateRef;
let firstName = '';
let lastName = '';
let email = '';
let address = '';
let telNumber = 0;
let gebDatum = '0';
const user = this.modalServiceUpdate.getUser();
this.loadedCourses = this.modalServiceUpdate.getUser().courses;
firstName = user.firstName;
lastName = user.lastName;
email = user.email;
address = user.address;
telNumber = user.telNumber;
gebDatum = '0';
this.userForm = new FormGroup({
firstName: new FormControl(firstName, Validators.required),
lastName: new FormControl(lastName, Validators.required),
email: new FormControl(email, Validators.required),
address: new FormControl(address, Validators.required),
telNumber: new FormControl(telNumber, Validators.required),
gebDatum: new FormControl(gebDatum, Validators.required),
});
}
saveData() {}
}
the second issue , if I don't use the ngDoCheck() , the data that comes from other Component(Component A) will not be fired before the onUpdate() is called. so with ngOnInit() I will get undefined or empty userData .
is there alternative that can I use , to inform Angular about any changes happen on the userData that saved in Service.ts ?
I hope that some one can help me .
Thank you
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']);
}