问题
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');
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