In this scenario we have no connection between two components.
If you have parent/child scenario you can use @Input, @Output
system of angular (explained in other places).
The ingredients for our recipe are:
- 1 EventEmitter
- 1 service
- 2 components
We can start adding a service with, inside it, an event emitter.
Sign-in service 💾
// ~/sign-in.service.ts
import { EventEmitter, Injectable } from '@angular/core';
@Injectable()
export class SignInService {
public username = new EventEmitter<string>();
constructor() { }
}
Now we create our example components to use it.
Header component 💾
// ~/header.component.ts
import { Component, OnInit } from '@angular/core';
import { SignInService } from '../sign-in.service';
@Component({
selector: 'app-header',
template: `<header>
Hello<span *ngIf="username">{{' ' + username}}</span>!
</header>`,
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
public username;
constructor(private _signInService: SignInService) {
this._signInService.username.subscribe(
(data: string) => {
this.username = data;
});
}
ngOnInit() {
}
ngOnDestroy() {
this._signInService.username.unsubscribe();
}
}
With its style:
/* ~/header.component.css */
header {
box-sizing: border-box;
height: 60px;
width: 100%;
background-color: #1389fd;
color: white;
position: absolute;
top: 0;
right: 0;
left: 0;
line-height: 40px;
padding: 10px 10%;
font-family: Lato;
font-size: 24px;
text-align: right;
}
Sign-in component 💾
// ~/sign-in.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { SignInService } from '../sign-in.service';
@Component({
selector: 'app-sign-in',
templateUrl: './sign-in.component.html',
styleUrls: ['./sign-in.component.css']
})
export class SignInComponent implements OnInit {
public username: string;
constructor(private _signInService: SignInService) {}
public handleSubmit(f: NgForm): void {
console.log(this.username);
this._signInService.username.emit(this.username);
}
ngOnInit() {}
}
With its template and style:
<!-- ~/sign-in.component.html -->
<form #f="ngForm" (ngSubmit)="handleSubmit(f)">
<!-- username field -->
<label for="username">Username: </label>
<input #usr="ngModel" id="username" name="username"
[(ngModel)]="username" class="form-control" required minlength="3">
<!-- submit button -->
<button type="submit" class="btn btn-primary">SEND</button>
</form>
/* ~/sign-in.component.css */
form {
box-sizing: border-box;
background-color: white;
color: black;
padding: 10px 10%;
font-family: Lato;
font-size: 18px;
text-align: center;
}
Now, when we click on submit Send
button we can see our username inserted in the header component.
Here you can see a working example:
Try it at home!
Like!! I blog frequently and I really thank you for your content. The article has truly peaked my interest.