How to render html from server in angular 6

4k Views Asked by At

I have a client side blog app that shows list of articles when loaded. I want to load the article data from server including the dynamic meta tags of that page for SEO purposes

For example:

  1. I click on a link: https://www.techstack21.com/article/function-returning-other-functions-in-javascript

Where I want make a GET request with query string /?url=function-returning-other-functions-in-javascript and render template from server to client similar to pug or jade templating engines.

How do I achieve this in angular 6?

I don't want to render complete app on server but only for particular urls with query strings as example above

2

There are 2 best solutions below

0
On

This is not possible with Angular. You may only render pure HTML in template using [innerHTML], but then you can not interract with it the angular way.

The good practice is to communicate with a server (using POST/GET requests...) which will send you back serialised "JSON" data of your articles. Then you can render that unserialised JSON data you received from the server with angular components.

You may want to take a look at REST app. :)

0
On

You can use Meta Service to update your meta data from your API

online example

enter image description here

import { Component } from '@angular/core';
import { Meta } from '@angular/platform-browser';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  constructor(
    private meta: Meta,
    private http: HttpClient
  ) { }

  getMetaData$() {
    const isDevMode = true;
    if (isDevMode) {
      const mockMetas = {
        ['twitter:card']: 'summary',
        'title': 'myTitle',
        'description': 'myDesc'
      }
      return of(mockMetas);
    } else {
      return this.http.get('/?url=function-returning-other-functions-in-javascript')
    }
  }

  ngOnInit() {
    this.getMetaData$().subscribe((metas) => {
      for (const key of Object.keys(metas)) {
        this.meta.updateTag(
          { name: key, content: metas[key] },
        );
      }
    })
  }
}