Angular指令-如何添加锚点并将routerlink设置为dom元素
我想创建一个结构方向,它将Angular指令-如何添加锚点并将routerlink设置为dom元素,angular,angular-routing,angular-directive,Angular,Angular Routing,Angular Directive,我想创建一个结构方向,它将 <any-dom-element anchorDirective="baseRoute">{{itemId}}</any-dom-element> 到 到目前为止我有 import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core'; @Directive({ selector: '[anchorDirective]' }) export clas
<any-dom-element anchorDirective="baseRoute">{{itemId}}</any-dom-element>
到
到目前为止我有
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
@Directive({ selector: '[anchorDirective]' })
export class AnchorDirective {
@Input() set sbAnchor(baseRoute: string) {
const a = document.createElement('a');
a.href = baseRoute;
// <------ How to insert the anchor, so that it will work with angulars router?
this.viewContainer.createEmbeddedView(this.templateRef)
}
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
}
所以我的问题是
如何插入已创建的锚点
如何使创建的锚与angulars路由器一起工作?
对你的两个具体问题的简短回答是:这是不可能的 从Angular 8开始,在这种情况下不可能向任何元素动态添加指令routerLink。有一种将指令应用于组件主体元素的能力。虽然这个问题并不是你想要的,但它们有一些共同点。如果可以向任何元素动态添加指令,那么也可以将其应用于组件宿主元素 如果您不关心您追求的特性的具体实现细节,那么下面是一个替代方法的建议 我建议将锚点实现为具有属性选择器而不是结构指令的组件:
@Component({
selector: '[anchor]', // <-- The component selector can be an attribute, it doesn't have to be an element tag.
templateUrl: './anchor.component.html',
styleUrls: ['./anchor.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AnchorComponent implements OnInit {}
感谢您提供有关组件选择器作为属性的信息。然而,它并没有回答我在下面贴出的两个问题。我想知道如何使用结构指令插入Dom元素,在本例中应用路由功能我同意我没有回答您的两个具体问题。我已经更新了我的答案。希望这更有帮助。
@Component({
selector: '[anchor]', // <-- The component selector can be an attribute, it doesn't have to be an element tag.
templateUrl: './anchor.component.html',
styleUrls: ['./anchor.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AnchorComponent implements OnInit {}
<div [anchor]="baseRoute"></div>
<h1 [anchor]="baseRoute"></h1>
<p [anchor]="baseRoute"></p>
<some-angular-component [anchor]="baseRoute"></some-angular-component>
Template parse errors:
More than one component matched on this element.