Is there a way to dynamically set an element name in angular template?

时间:2019-04-17 02:47:31

标签: angular angular-template

I am not talking about HTML forms here or element attributes named "name".

I am wondering if there is a way to conditionally choose the output HTML element name when using angular templates?

Essentially, I want to do this:

<ng-container *ngElementName="href() ? 'a' : 'span'" [routerLink]="href()">{{ caption() }}</ng-container>

With the expected output, when href() returns something:

<a href="/href-location">href supplied, caption</a>

And this, when href() returns noting:

<span href="">href missing, caption</span>

Thank you kindly.

1 个答案:

答案 0 :(得分:0)

我会考虑不使用函数,但是可以使用ngIf来实现。您不能在跨度上放置href。

<a [href]="href()" *ngIf="href()">href supplied, caption</a>
<span *ngIf="!href()">href missing, caption</span>

或使用模板,这样就不会多次调用href()函数。

<ng-content *ngIf="href() as href else noHref">
  <a [href]="href">href supplied, caption</a>
</ng-content>
<ng-template #noHref>
  <span>href missing, caption</span>
</ng-template>

或创建一个将href用作输入属性的组件,并在组件模板中执行上述操作,如果您在许多地方重复此操作,则可以节省重复的标记。

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-link',
  templateUrl: './link.component.html',
  styleUrls: ['./link.component.css']
})
export class LinkComponent {
  @Input()
  href: string;
}

带有模板

<a [href]="href" *ngIf="href"><ng-container *ngTemplateOutlet="content"></ng-container></a>
<span *ngIf="!href"><ng-container *ngTemplateOutlet="content"></ng-container></span>
<ng-template #content>
  <ng-content></ng-content>
</ng-template>

并像使用它

<app-link [href]="href()">caption</app-link>