简体   繁体   English

如何在Angular模板中动态更改属性名称?

[英]How to dynamically change attribute name in Angular template?

How to dynamically change which property is set on an HTML element in the template? 如何动态更改模板中HTML元素上设置的哪个属性?

I have an anchor wrapper component, which accepts both href and routerLink properties. 我有一个锚定包装器组件,该组件同时接受hrefrouterLink属性。 Only one of them needs to be set. 只需要设置其中之一。 I want to write it's template, so that I'm setting only one of href and routerLink attributes on <a> element, whichever is defined. 我想编写它的模板,以便我在<a>元素上仅设置hrefrouterLink属性之一,无论定义了哪个。

Is it possible without separately defining both cases with *ngIf ? 是否可以不用*ngIf分别定义两种情况?

anchor.component.ts 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 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>

Well instead of binding an attribute/directive, you should bind an event : 好吧,应该绑定一个事件,而不是绑定一个属性/指令:

<a (click)="doSomething($event)">My link</a>
doSomething(event: MouseEvent) {
  if (condition) this.router.navigate(url); // [routerLink]
  else window.location.href = url; // href
}

EDIT If you want to achieve that, simply put this code into a directive 编辑如果要实现这一目标,只需将这段代码放入指令中

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM