Angular universal Server Side Rendering, Meta tags

旧时模样 提交于 2019-12-01 22:15:43

问题


I moved my site to Angular universal SSR, during my move I encountered some problems that I thought ng-universal would fix.

I want to add meta tags such as description, keywords etc (different for each page).

Using the titleService as angular suggests works just fine, it changed the title of the pages. However if I land on homepage and then navigate from there to other pages, the title is not changing, but when I look on source I see the change in the source but no on the tab of VIEW. If I land on the page (or hit refresh) the page is updated with the correct title.

I tried to add in additional to the title meta tags, but nothing works:

this.meta.updateTag( {name: "description", content: 'test1234});

this.meta.addTag({name: 'description', content: 'Content description' });

OR

using vanilaJS
 var doc = (<HTMLMetaElement>document.getElementById('description'));
doc.content = "test1234";

the meta is not changing in the header section. I have no idea why. any help can assist.. thanks


回答1:


To set meta tags for Angular Universal-SSR (tried only on Angular 2), you should use Renderer. To set for example title(or update it), you can do it on this way: Link for solution

To set meta tags, you need to: 1.Import Renderer and Document

import { Renderer } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

2.Add these dependencies to constructor:

@Inject(DOCUMENT) private document: any,
private renderer: Renderer

3.Add meta tags -example

//-- Create new meta element inside of head tag
let elem = renderer.createElement(document.head, "meta");

//-- Set meta attributes
renderer.setElementAttribute(elem, 'name', 'description');
renderer.setElementAttribute(elem, 'content', 'Some test decription');
  1. When you open "view page source", it should result like this inside of head tag:

    < meta name="description" content="Some test description" >



来源:https://stackoverflow.com/questions/49169175/angular-universal-server-side-rendering-meta-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!