'Is there a way to dynamically bind Angular directives?

I'm building a component that should be as reusable as possible. The current case is a modal which should allow the developer to show/hide the allowed buttons (primary:confirm, secondary:cancel).

We have to use a style library that works with directives. I tried using a loop to add all buttons and set the directive dynamically. This doesn't work though. Simply "nothing" happens.

<button
  *ngFor="let button of buttons"
  [attr.primary-button]="button.type === 'primary'"
  [attr.secondary-button]="button.type === 'secondary'"
  (click)="..."
  [class]="button.class"
  [disabled]="button.disabled"
>
  {{ button.text }}
</button>

I'm aware that a directive is not an attribute but couldn't find any other ideas for this problem.



Solution 1:[1]

Currently this behaviour is not supported by Angular, it is however on their roadmap.

As a workaround, you would need to actually separate the buttons using *ngIf. Not ideal, (or very elegant for that matter) but it does work.

<ng-container *ngFor="let button of buttons">
  <button
    *ngIf="button.type === 'primary'"
    [class]="button.class"
    [disabled]="button.disabled"
    primaryButton
  >
    {{ button.text }}
  </button>

  <button
    *ngIf="button.type === 'secondary'"
    [class]="button.class"
    [disabled]="button.disabled"
    secondaryButton
  >
    {{ button.text }}
  </button>
</ng-container>

There is also an open issue for this on Github, which has been active since 2016.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Doye