39
loading...
This website collects cookies to deliver better user experience
// book.service.ts
import { Injectable } from '@angular/core';
import { Book } from './models';
@Injectable({ providedIn: 'root' })
export class BookService {
private favBooks: Book[] = [
{ title: 'Principles' },
{ title: 'The Story of Success' },
{ title: 'Extreme Economies' },
];
getBooksList() {
return this.favBooks;
}
createBook(bookTitle: string) {
// simple check, title must be at least 1 char
if (bookTitle.length !== 0) {
const bookObj = { title: bookTitle };
this.favBooks.push(bookObj);
}
}
}
// one.component.html
<div>
<input
type="text"
placeholder="Write a title"
#titleInput />
<button (click)="onAddBook()">Add Title</button>
</div>
#titleInput
. This is used to get direct access to the element in the DOM and it is not a good practice. However, it is the easiest way to get input data from users and focus on the service itself. this.titleInputReference.nativeElement.value
gets the user data from the input element.// one.component.ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { BookService } from '../book.service';
@Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.css'],
})
export class OneComponent {
@ViewChild('titleInput')
titleInputReference!: ElementRef;
constructor(private bookService: BookService) {}
onAddBook() {
this.bookService.createBook(
this.titleInputReference.nativeElement.value
);
}
}
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { BookService } from './book.service';
import { Book } from './models';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
title = 'Passing Data with Angular Services';
booksList: Book[] | undefined;
constructor(private bookService: BookService) {}
ngOnInit(): void {
this.booksList = this.bookService.getBooksList();
}
}
// app.component.html
<div>
<h1>{{ title }}</h1>
<hr />
<div>
<app-one></app-one>
<app-two></app-two>
</div>
<hr />
<div *ngIf="booksList" class="wrapper">
<div *ngFor="let book of booksList" class="book">
{{ book.title }}
</div>
</div>
</div>