【问题标题】:Reading routing parameter in HTML在 HTML 中读取路由参数
【发布时间】:2017-09-23 16:34:01
【问题描述】:

我们可以通过HTML来设置路由参数:

<a [routerLink] = "['/api/foo/', id]"/>

我知道我们可以通过处理typescript中的事件来读取路由参数:

import {OnInit, OnDestroy, Component} from '@angular/core';

@Component({...})
export class MyComponent implements OnInit{

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    // subscribe to router event
    this.activatedRoute.params.subscribe((params: Params) => {
        let Id = params['id'];
        console.log(Id);
      });
  }
}

但是,有没有办法在 HTML 中读取路由参数,而不是在 TypeScript 组件中?

我想以如下方式使用:

<a href="api/foo/[routerLink]"/>

【问题讨论】:

  • 是什么阻止您阅读组件中的参数?
  • 告诉我你在 HTML 的什么地方使用它?
  • 你不能这样用,就是不行
  • @RomanC 这是我的问题。有没有办法在 HTML 中使用router
  • @downvoter 投反对票的理由是什么?

标签: javascript angular typescript angular2-routing


【解决方案1】:

如果你想在 html 中获取参数,最好将参数分配给一个变量并在 html 中使用它

private param:number;

private ngOnInit() {
    // subscribe to router event
    this.activatedRoute.params.subscribe((params: Params) => {
        this.param = params['id'];
        console.log(this.param);
      });
  }

在你的 html 中

<div>{{param}}</div>

【讨论】:

  • 我不确定 OP 是否想要这个。
【解决方案2】:

如果你想获取 id 作为数字。你可以使用这个。

id:number;

 ngOnInit() {

        this.subscription = this.activatedRoute.params.subscribe(
          (params: any) => {
            if (params.hasOwnProperty('id')) {
               id= +params['id'];
              //do whatever you want
            }
          }
        );

      }

这破坏了订阅

ngOnDestroy() {
    this.subscription.unsubscribe();
  }

您可以访问 html 端的 id 字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2016-10-11
    • 2013-04-22
    • 2014-11-19
    相关资源
    最近更新 更多