Dynamically add meta description based on route in Angular

前端 未结 5 1108
自闭症患者
自闭症患者 2020-12-23 10:55

I\'m using Angular 5 to build a small brochure type website. Thus far, I have my routes set up, and the page title changes dynamically based on the activated route. I got th

5条回答
  •  伪装坚强ぢ
    2020-12-23 11:37

    Here are the relevant parts from my project. (Angular 2/4)


    app-routing.module.ts:

    Routes:

    ... const appRoutes: Routes = [
        {
            path: 'path1', loadChildren: './path1#path1Module',
            data: {
                title: '...',
                description: '...',
                keywords: '...'
            }
        },
        {
            path: 'path2', loadChildren: './path2#path2Module',
            data: {
                title: '...',
                description: '...',
                keywords: '...'
            }
        } ...
    

    app.component.ts (or your bootstrap component):

    imports:

    // imports
    import { Component, OnInit} from '@angular/core';
    import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
    import 'rxjs/add/operator/filter';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/mergeMap';
    import { Title,Meta } from '@angular/platform-browser';
    

    constructor:

        // constructor:
            constructor(private router: Router,
                        private route: ActivatedRoute,
                        private titleService: Title, private meta: Meta) {}
    

    ngOnInit() method:

    ngOnInit() {
    
            this.router.events
                .filter((event) => event instanceof NavigationEnd)
                .map(() => this.route)
                .map((route) => {
                    while (route.firstChild) route = route.firstChild;
                    return route;
                })
                .filter((route) => route.outlet === 'primary')
                .mergeMap((route) => route.data)
                .subscribe((event) => {
                    this.updateDescription(event['description'], event['keywords'], event['title']);
                });
    
        }
    

    method that updates title and meta tags -> called from ngOnInit():

    updateDescription(desc: string, keywords: string, title: string) {
        this.titleService.setTitle(title);
        this.meta.updateTag({ name: 'description', content: desc })
        this.meta.updateTag({ name: 'keywords', content: keywords })
        this.meta.updateTag({ name: 'og:title', content: title })
        this.meta.updateTag({ name: 'og:description', content: desc })
    }
    

    Hope it helps.

提交回复
热议问题