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

时间:2018-10-12 08:51:02

标签: html angular typescript angular-template

如何动态更改模板中HTML元素上设置的哪个属性?

我有一个锚定包装器组件,该组件同时接受hrefrouterLink属性。只需要设置其中之一。我想写它的模板,以便我只在href元素上设置routerLink<a>属性之一,以定义为准。

是否可以不用*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>

1 个答案:

答案 0 :(得分:1)

应该绑定一个事件,而不是绑定一个属性/指令:

copyToClipboard(item) {
    document.addEventListener('copy', (e: ClipboardEvent) => {
      e.clipboardData.setData('text/plain', (item));
      e.preventDefault();
      document.removeEventListener('copy', null);
    });
    document.execCommand('copy');
  }
#include <stdio.h>
void countTwo2(int num, int *result);

int main()
{
    int number, result;
    printf("Enter the number: \n");
    scanf("%d", &number);
    countTwo2(number, &result);
    printf("countTwo2(): %d\n", result);
    return 0;
}

void countTwo2(int num, int *result)
{
    if(num > 0) {
       if((num % 10)/2 == 1) {
           *result += 1;
       }
       countTwo2(num/10, result);
    }

}

编辑如果要实现这一目标,只需将这段代码放入指令中即可

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