Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 input on a directive in angular

Tags:

angular

I have a directive in angular 11 with the following inputs :

@Directive({
  selector: "[appHasToken]",
})
export class HasTokenDirective implements OnInit, OnDestroy {
  @Input("appHasToken") fallback: TemplateRef<any>;
  @Input("showWarning") showWarning = false;
//...
}

I call it in my code like this :

<ng-container *appHasToken="noToken">

Now in a single place, I want the showWarning to true, so I did

<ng-container *appHasToken="noToken;" [showWarning]="true">

but I am prompted with

Can't bind to 'showWarning' since it isn't a known property of 'ng-container'

now, I know I can rename the input with a different name than the directive and do

<ng-container appHasToken [templateRef]="noToken" [showWarning]="true">

but what about keeping the same stuff I was doing, is there a fix ?

like image 495
Crocsx Avatar asked Dec 02 '25 09:12

Crocsx


1 Answers

When you write a directive with * (structural directive), angular adds an ng-template around your element, so <ng-container *appHasToken="noToken"> gets translated to:

<ng-template [appHasToken]="noToken">
  <ng-container></ng-container>
</ng-template>

When you have another input, the second input remains on the ng-container, and since the directive isn't there anymore, angular throws because the now ng-container doenst have a known property showWarning. To overcome this, there is microsyntax in angualr which allows passing more than one input to the structural directive - you add the directive name in the input naming before the input's name, so showWarning becomes appHasTokenShowWarning (notice the uppercase in the first word), and then can be accessed in the following way:

<ng-container *appHasToken="noToken; showWarning true">

if this reminds you of ngFor its because ngFor also uses this! here is the source code

Here is a stackblitz, and note your inputs should look like the following:

export class HasTokenDirective implements OnInit, OnDestroy { @Input("appHasToken") fallback: TemplateRef; @Input("appHasTokenShowWarning") showWarning = false; //... }

like image 179
Moshezauros Avatar answered Dec 04 '25 02:12

Moshezauros