I recently started working with Angular and came across a logic issue while implementing a function using a service class in my component class. Here is the code snippet that I encountered:
app.module.ts
@NgModule({
declarations: [
AppComponent,
AddUserComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { UserService } from './services/user.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService]
})
export class AppComponent implements OnInit {
title = 'UserAvailabe';
constructor(private userService: UserService) {
}
pusers: { name: string; status: string; }[] = [];
ngOnInit() {
this.pusers = this.userService.users;
console.log("ngOnInit called");
}
}
app.component.html
<div class="container">
<app-add-user></app-add-user>
<div class="user-div" *ngFor="let user of pusers">
<div class="user-name">{{user.name}}</div>
<div class="user-status">{{user.status}}</div>
</div>
</div>
add-user.component.ts
import { UserService } from './../services/user.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-add-user',
templateUrl: './add-user.component.html',
styleUrls: ['./add-user.component.css']
})
export class AddUserComponent implements OnInit {
username: string = '';
status: string = 'active';
constructor(private userService: UserService) { }
ngOnInit(): void {
}
addUser() {
this.userService.addNewUser(this.username, this.status);
console.log("addUser() called");
console.log(this.userService.users);
}
}
add-user.component.html
<div class="form">
<div class="uName">
<input type="text" placeholder="Username" id="username" [(ngModel)]="username">
</div>
<div class="uStatus">
<select name="status" id="status" [(ngModel)]="status">
<option value="active">active</option>
<option value="inactive">inactive</option>
</select>
</div>
<div class="cUser">
<button (click)="addUser()">Create User</button>
</div>
</div>
user.service.ts
export class UserService {
constructor() { }
users = [
{ name: 'John', status: 'active' },
{ name: 'Mark', status: 'inactive' },
{ name: 'Steve', status: 'active' }
]
addNewUser(pname: string, pstatus: string) {
this.users.push({ name: pname, status: pstatus });
}
}
As per my understanding, initially, the pusers
array in app.component.ts
gets populated from the service class using ngOnint()
. However, when I add a new user by calling the addUser()
method in app.service.ts
, it updates the users
array. Surprisingly, the pusers
array in app.component.ts
also gets automatically updated without calling ngOnInit()
or any other updateData() methods. How does this happen?
Note: Please excuse me if my question seems incorrect. Thank you for your assistance :)