在routerLink中设置url字符串

时间:2018-05-22 13:12:31

标签: angular angular-routing angular-router

我的组件公共变量url和标题字符串如下:

<button type="button" class="nsg-button nsg-bg--black register-next-step-cta js-nextStepCta">FORTSÄTT</button>

我想在我的模板中使用它来获取这样的链接:

# These are the two dataframes
train = to_spark_df("train.csv")
test = to_spark_df("test.csv")

# These are the labels of the six classes
labels = [i for i in train.columns if i not in ["id", "comment_text"]]

tokenizer = Tokenizer(inputCol="comment_text", outputCol="words")
wordsData = tokenizer.transform(train)

word2vec = Word2Vec(inputCol = "words", outputCol = "rawFeatures")
model = word2vec.fit(wordsData)
result = model.transform(wordsData) # This is the feature vector extracted with Word2Vec

问题是生成的链接都是错误的。我知道routerLink可以静态使用字符串,但是如何为模板提供变量,因为这种方式不起作用:

const url: string = 'locator;name=Test';
const title: string = 'Test';

我该如何解决这个问题?我从服务中收到这些链接,我无法重构它。现在我正在解决这个问题,但我有问题,因为每次点击这些链接都会重新加载网页:

<a mat-button [routerLink]="'/' + url">{{title}}</a>

4 个答案:

答案 0 :(得分:1)

尝试以下语法使其成为url变量dyamic:

[routerLink]="['/', url]"

答案 1 :(得分:0)

您可能想尝试这种语法:

<a routerLink="/{{url}}"></a>

过去我的成功。 也适用于*ngFor循环。

答案 2 :(得分:0)

好:routerLink = "/{{url}}"

最佳:[routerLink] = " '/' + url "

<强>更新

[routerLink]="[" '/' + getUrl(url) ", {queryParams: {name: title}}]
组件中的

const url: string = 'locator;name=Test';
const title: string = 'Test';

getUrl(url:string):string {
    let res = url.split(";");
    return res[0];
}

答案 3 :(得分:0)

这是适合我的解决方案。以上所有解决方案都基于处理我的有效输入网址。处理完一些字符后,一些字符被替换,未转义等...此解决方案根本不更改url字符串并在导航期间使用它。它基于angular github的routerLink源。在我的特定情况下,我只留下了我需要的功能。

import { Attribute, Directive, ElementRef, HostBinding, HostListener, Input, OnChanges, OnDestroy, Renderer2, isDevMode } from '@angular/core';
import { LocationStrategy } from '@angular/common';
import { Router, ActivatedRoute, RouterEvent, NavigationEnd, UrlTree } from '@angular/router';
import { Subscription } from 'rxjs';

@Directive({ selector: 'a[routerUrlLink]' })
export class RouterUrlLinkWithHref implements OnChanges, OnDestroy {

    @HostBinding('attr.target') @Input() target: string;
    @Input() skipLocationChange: boolean;
    @Input() replaceUrl: boolean;

    private url: string;
    private subscription: Subscription;
    private preserve: boolean;

    // the url displayed on the anchor element.
    @HostBinding() href: string;

    constructor(
        private router: Router,
        private locationStrategy: LocationStrategy) {
        this.subscription = router.events.subscribe((s: RouterEvent) => {
            if (s instanceof NavigationEnd) {
                this.updateTargetUrlAndHref();
            }
        });
    }

    @Input()
    set routerUrlLink(url: string | UrlTree) {
        if (url instanceof UrlTree) {
            this.url = url.toString();
        } else {
            this.url = url;
        }
    }

    @Input()
    set preserveQueryParams(value: boolean) {
        if (isDevMode() && <any>console && <any>console.warn) {
            console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
        }
        this.preserve = value;
    }

    ngOnChanges(changes: {}): any { this.updateTargetUrlAndHref(); }
    ngOnDestroy(): any { this.subscription.unsubscribe(); }

    @HostListener('click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey'])
    onClick(button: number, ctrlKey: boolean, metaKey: boolean, shiftKey: boolean): boolean {
        if (button !== 0 || ctrlKey || metaKey || shiftKey) {
            return true;
        }

        if (typeof this.target === 'string' && this.target != '_self') {
            return true;
        }

        const extras = {
            skipLocationChange: attrBoolValue(this.skipLocationChange),
            replaceUrl: attrBoolValue(this.replaceUrl),
        };
        this.router.navigateByUrl(this.url, extras);
        return false;
    }

    private updateTargetUrlAndHref(): void {
        this.href = this.locationStrategy.prepareExternalUrl(this.url);
    }

}

function attrBoolValue(s: any): boolean {
    return s === '' || !!s;
}

如何使用它。 导入到您的模块,并在模板中使用它:

<a mat-button [routerUrlLink]="'/' + urlStringOrUrlTree">Link Label</a>