Our first component
Let's make this simple component that will serve you with Shakespeare quote every time you reload the page.
Github Code for this component

To create a new Component
- Run the following command in Angular CLI
-
ng generate component header - Add bootstrap CDN links and google font links in index.html folder
Let's take a quick look at the code
header.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'shakespeare-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
quotes: String[] = [
"Shall I compare thee to a summer's day?\nThou art more lovely and more temperate:\nRough winds do shake the darling buds of May,\nAnd summer's lease hath all too short a date",
"The common curse of mankind, - folly and ignorance",
"Nature teaches beasts to know their friends"
]
item: String = ""
ngOnInit(): void {
this.item = this.quotes[Math.floor(Math.random() * this.quotes.length)];
}
}
header.component.html
<div class="old-english ">
<header class="header">
<div class="heroimage">
<img class="rounded-circle" alt="100x100"
src="../assets/Cartoon-of-William-Shakespeare-dancing-hip-hop-592140.jpg">
</div>
<h2 class="appname">Will-i-am</h2>
</header>
</div>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4 my">Shakespeare Once Said</h1>
<p class="quote">{{item}}</p>
</div>
</div>
Text interpolation and lifecycles hooks
Whenever the page is reloaded the components' ngOnInit() function run to assign the variable item a random quote from the String of quotes.
We can use interpolation to display the value of this item variable in the corresponding component in the template using {{ }}.
4
