Could someone help me understand why I am unable to pass data from the child component to the parent component with a variable value? It seems that changes made in the child component are not reflecting in the parent component. Is it possible that the @Output decorator only works with click events triggered in the child component? I also experimented with using event emitters within different methods like the constructor or ngOnInit, but still no luck.
Child component:
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-server',
templateUrl: './server.component.html',
styles: [
`.online {
color: white;
}
`
]
})
export class ServerComponent {
serverId: number = 10;
serverStatus: string = 'offline';
serverName: 'Random server';
@Output() serverNameEmitter = new EventEmitter<string>();
constructor() {
this.serverStatus = Math.random() > 0.5 ? 'online' : 'offline';
}
ngOnInit(): void {
this.passServerName(this.serverName);
}
passServerName(serverName: string) {
this.serverNameEmitter.emit(serverName);
}
getColor() {
return this.serverStatus == 'online' ? 'green' : 'red';
}
getServerStatus() {
return this.serverStatus;
}
}
Parent component
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css'],
})
export class ServersComponent implements OnInit {
allowNewServer = false;
serverCreationStatus = 'No server was created!';
serverNames = "";
serverStatus = false;
servers = [];
serverName = {
name: "Test server"
};
constructor() {
setTimeout(() => {
this.allowNewServer = true;
}, 2000);
}
ngOnInit(): void {}
onCreateServer() {
this.serverStatus = true;
this.servers.push(this.serverName.name);
this.serverCreationStatus = 'Server has been created! Name is ' + this.serverName.name;
}
onUpdateServerName(event: Event) {
this.serverNames = (event.target as HTMLInputElement).value;
}
changeServerName() {
this.serverName.name = this.serverNames;
}
gettingServerName(serverName: string) {
this.serverNames = serverName;
}
}
Parent component HTML
<label>Server Name</label>
<input type="text" class="form-control" (input)="onUpdateServerName($event)">
<button class="btn btn-primary" [disabled]="!allowNewServer"
(click)="onCreateServer()">Add Server</button>
<p>Here's {{ serverNames }}</p>
<p *ngIf="serverStatus; else noServer">Server was created, server name is {{
serverName.name }}</p>
<ng-template #noServer>
<p>No server was created!</p>
</ng-template>
<button class="btn btn-primary" (click)="changeServerName()">Change server name</button>
<app-server *ngFor="let server of servers"
(serverNameEmitter)="gettingServerName($event)"></app-server>