2

I'm creating a wrapper component for an existing 3rd party component. The goal is to augment the 3rd party's functionality with some custom styles and logic.

The 3rd party component is configured using different directives. My first idea was to conditionally apply these directives, which is currently not possible with Angular.

So I came up with multiplying the same markup in my template (which is bad) and conditionally displaying it, based on *ngIf conditions. The 3rd party component also provides content projection, which I also want to leverage within my wrapper component. However, it seems like only the projected content will only be displayed in the last / lowest <ng-content></ng-content> within the template. How can I enforce the projected content to be rendered in each of the <ng-content>'s?

Relevant code:

file: my-button.component.ts

@Component({
  selector: 'my-button',
  templateUrl: 'my-button.component.html',
  styleUrls: [ 'my-button.component.scss' ],
  encapsulation: ViewEncapsulation.None // since I want to overwrite some of the 3rd party component's style
})    
export class MyButtonComponent {    
  @Input()
  public isCircle: boolean = false;
}

file: my-button.component.html

<button *ngIf="!isCircle" mat-button>
  <ng-content></ng-content>      
</button>

<button *ngIf="isCircle" mat-fab>
  <ng-content></ng-content>
</button>

usage / parent component's template:

<!-- This renders '<button mat-button></button>', and hence is never displayed -->
<my-button>
  rectangle-shaped button
</my-button>

<!-- This will be displayed correctly, because it's the most recent projected content -->
<my-button [isCircle]="true">
  circular button
</my-button>
Ronin
  • 7,322
  • 6
  • 36
  • 54
  • 1
    show full code please – Max Koretskyi Dec 04 '17 at 19:51
  • @AngularInDepth.com updated – Ronin Dec 04 '17 at 21:47
  • _How can I enforce the projected content to be rendered in each of the 's_ - you can't, since there's only one node created in DOM which is being projected. And why do you have the same markup inside ` – Max Koretskyi Dec 05 '17 at 06:25
  • It’s actually a workaround/hack for displaying directives conditionally. – Ronin Dec 05 '17 at 07:31
  • I.e. if the ‘isCircle’ flag is passed, I want to apply the ‘mat-fab’ directive. Else, I want to apple the ‘mat-button’ directive. – Ronin Dec 05 '17 at 07:35
  • Those directives each apply a css class to the component. But I can't apply classes to the child, but only to the current component. – Ronin Dec 05 '17 at 07:52

0 Answers0