[英]How to dynamically change attribute name in Angular template?
如何動態更改模板中HTML元素上設置的哪個屬性?
我有一個錨定包裝器組件,該組件同時接受href
和routerLink
屬性。 只需要設置其中之一。 我想編寫它的模板,以便我在<a>
元素上僅設置href
和routerLink
屬性之一,無論定義了哪個。
是否可以不用*ngIf
分別定義兩種情況?
anchor.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'my-anchor',
templateUrl: './anchor.component.html',
styleUrls: ['./anchor.component.scss'],
})
export class AnchorComponent implements OnInit {
@Input() public label: string;
// Only one of href and routerLink must be specified
@Input() public href?: string;
@Input() public routerLink?: string;
ngOnInit() {
this.ensureEactlyLinkTargetDefined();
}
private ensureEactlyLinkTargetDefined(): void {
if (!((this.href && !this.routerLink) || (!this.href && this.routerLink))) {
throw new Error("Exactly one of the properties 'href' and 'routerLink' must be defined");
}
}
}
anchor.component.html
<a
<!--
Here lies the problem. I only want to set one of those
attributes, not both simultaneously, as then href is not
respected, as routerLink directive overwrites it
-->
[href]="href"
[routerLink]="routerLink"
<!--
Something like [attr]="setAttribute(attributeName, attributeValue)"
-->
>
{{ label }}
</a>
好吧,應該綁定一個事件,而不是綁定一個屬性/指令:
<a (click)="doSomething($event)">My link</a>
doSomething(event: MouseEvent) {
if (condition) this.router.navigate(url); // [routerLink]
else window.location.href = url; // href
}
編輯如果要實現這一目標,只需將這段代碼放入指令中
@Directive({ selector: 'navigator' })
export class NavigatorDirective {
@Input('navigator.condition') condition: boolean;
constructor(private router: Router) {}
@HostBinding('click', ['$event'])
doSomething(event: MouseEvent) {
if (this.condition) this.router.navigate(url); // [routerLink]
else window.location.href = url; // href
}
}
<a [navigator]="url" [navigator.condition]="myCondition">My link</a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.