【问题标题】:Route to an id or class in a component in Angular?路由到 Angular 组件中的 id 或类?
【发布时间】:2018-11-03 01:55:49
【问题描述】:

我是 Angular 的新手,在 Angular 中,每当我们创建路由时,我们都会为不同的组件定义它,即我们定义 pathcomponent 。假设我在组件 A 上,路径为 /A 。现在假设我想转到A.component.html 中的特定id。如何通过路由来实现这一点(如果可能的话,为它定义一个特定的路径,比如/A#id

【问题讨论】:

    标签: angular typescript routing angular2-routing angular4-router


    【解决方案1】:

    首先,您在这里要实现什么以及“转到A.component.html中的特定ID”是什么意思,目前尚不清楚。

    您是否尝试从另一个组件路由到 /A#id?

    您应该能够通过角度路由将您的 id / 类名作为字符串传递。您只需要从路由参数中读取并执行您想要的操作。

    在您的应用程序路由中

    { path: 'A/:id', component: AComponent },
    

    在您的 AComponent .ts 中

    import { Component, OnInit } from "@angular/core";
    import { ActivatedRoute } from '@angular/router';
    
    @Component({
        selector: 'app-component-a',
        templateUrl: './a.component.html'
    })
    export class AComponent implements OnInit {
        constructor(private route: ActivatedRoute) {
            super();
         }
    
        public ngOnInit(): void {
            // This will get the param from your route
            this.route.params.subscribe((params) => {
                if (params) {
                    const idOrClassName= params['idOrClassName'];
                    if (idOrClassName) {
                        // Perform action when idOrClassName is presented
                        return;
                    } 
    
                    // Perform action when idOrClassName is not presented   
                }
            });
        }
    }
    

    【讨论】:

    • ID 应该是任何 DOM 元素的 id,例如 div
    • @AakashSingh 你想在这里实现什么?我的回答应该允许您通过角度路由将 id / classname 作为字符串传递。然后你的组件可以通过路由参数读取,你可以用它做任何你想做的事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多