要在Angular中绑定模板变量并使用基于活动的路由链接,可以按照以下步骤进行操作:
Link
@ViewChild
装饰器获取对模板变量的引用。例如,可以在组件类中添加以下代码:import { ViewChild, ElementRef } from '@angular/core';
export class YourComponent {
@ViewChild('linkRef') linkRef: ElementRef;
}
export class YourComponent {
@ViewChild('linkRef') linkRef: ElementRef;
getLinkHref(): string {
return this.linkRef.nativeElement.href;
}
setLinkHref(href: string): void {
this.linkRef.nativeElement.href = href;
}
}
这样,你就可以在组件类中通过调用getLinkHref()
方法获取活动链接的href
属性,或者通过调用setLinkHref(href)
方法设置活动链接的href
属性。
请注意,模板变量绑定的元素必须在视图中可见,否则ViewChild
装饰器将无法找到它。确保在需要访问模板变量之前,视图已经被渲染。