在 html 标签 Angular 5 中添加每页微数据

tec*_*ura 5 microdata angular

我正在开发 Angular 5 应用程序,但我陷入了困境。我想在 html 标签中动态添加特定于每个页面的微数据,例如

<html itemscope itemtype="http://schema.org/QAPage">
Run Code Online (Sandbox Code Playgroud)

有什么办法可以做到这一点吗?如果有的话请告诉我。

Tom*_*ula 4

对于结构化数据,google似乎推荐ld+json。查看结构化数据简介。如果您决定使用 ld+json 您可以使用如下内容:

@Component({
  selector: 'json-ld',
  template: ``,
  styleUrls: ['./json-ld.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class JSONLdComponent implements OnInit {
  private _json: SafeHtml;
  @Input()
  @HostBinding('innerHtml')
  set json(v: any) {
    this._json = this.getSafeHtml(v);
  }

  get json() {
    return this._json;
  }

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit() {}

  private getSafeHtml(value: object) {
    const json = value
      ? JSON.stringify(value, null, 2).replace(/<\/script>/g, '<\\/script>')
      : '';
    const html = `<script type="application/ld+json">${json}</script>`;
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}
Run Code Online (Sandbox Code Playgroud)

它以npm 包的形式提供。

如果您想<meta>向页面添加标签,请查看 Meta类。您可以将其注入任何组件并添加/删除/更新meta标签。