Search code examples
angularangular-template

How can I conditionally insert an atrribute into an Angular template


I have an angular component.

Cutting out the unneeded bits it's mostly like.

@Component({
  template: `
<a class="link-button" [href]="href">Link Button</a>
  `
})
export class LinkButtonComponent {
    @Input() href: string | null = '';
}

I have a CSS selector for links to nowhere that greys them out:

a.button-link:not([href]) {
    background-color:#A7A9AB;
    border-color:#A7A9AB;
}

However, binding a null value gives href="null" and does not remove the attribute completely.

How can I conditionally bind an attribute so it doesn't show up on null?


Solution

  • Use [attr.href] and the attribute will not be present in case of null value:

    <a class="link-button" [attr.href]="href">Link Button</a>
    

    Also, there is a typo in your code: button-link in CSS and link-button in HTML.