Search code examples
angulartypescriptangular-directiveangular-componentsng-zorro-antd

Inherit another UI library selector properties in a component attribute selector


I have a buildable/publishable Angular library which I want to wrap ng-zorro button (and other components as well one-by-one) within to add my attribute selector instead of the ng-zorro selector and add more properties to the original component.

In the source code of ng-zorro, you can see that the nz-button attribute is implemented like this:


@Component({
  selector: 'button[nz-button], a[nz-button]',
  exportAs: 'nzButton',
  preserveWhitespaces: false,
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <span nz-icon nzType="loading" *ngIf="nzLoading"></span>
    <ng-content></ng-content>
  `,
  host: {
    class: 'ant-btn',
    '[class.ant-btn-primary]': `nzType === 'primary'`,
    '[class.ant-btn-dashed]': `nzType === 'dashed'`,
    // ...
  }
})

As you can see it is not a @Directive but a @Component that selects elements with the condition button[nz-button].

Now this is the component I developed to wrap that component:

@Component({
  selector: 'button, a',
  preserveWhitespaces: false,
  imports: [
    NzButtonModule
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `<ng-content></ng-content>`,
  styleUrls: ['./button.component.scss'],
  standalone: true,
  host: {
    'nz-button': '',
    class: 'btn',
    '[class.btn-primary]': `color === 'primary'`,
    '[class.btn-secondary]': `color === 'secondary'`,
    // ...
  }
})

export class ButtonComponent {
  @Input() size: ButtonSize = 'md';
  @Input() shape: ButtonShape = 'default';
  @Input() color: ButtonColor = 'primary';
  @Input() fill: ButtonFill = 'solid';
  @Input() expand: ButtonExpand = 'default';
}

What I am trying to achieve is that the button tag I place in the consumer components has all the ng-zorro attributes and mine too so I can implement new attributes to the native tag and override the ant styles in some cases.

In other words, I want to have [nzType] (from ng-zorro) and shape (from my ButtonComponent) both on a <button> tag.


Solution

  • I ended up extending ng-zorro component to inherit its Inputs on my custom component it was not exactly what I wanted because now I have to use ng-zorro inputs by their name but not my desired name. For example, I have to use it like [nzSize] but not [size].

    It is a workaround that will do the work but not a solid and complete solution.

    I accept my solution until a better one comes.