Home > OS >  Material Angular using component's properties in directive
Material Angular using component's properties in directive

Time:01-23

I would like to use a property of tabs component (isActive) in a directive in the html, how can i do this?

see an exemple :

<mat-tab-group>        
    <div *ngFor="let elem of infosOnglet$ | async">
        <mat-tab isActive>
            <ng-template mat-tab-label>
               <app-export-menu [disabledButton]="I WANT USE THE BOOLEAN  IN CONDITION HERE">
               </app-export-menu>
        </mat-tab>
    </div>
</mat-tab-group>

Thanks for all

CodePudding user response:

Just use a template reference variable

    <mat-tab #tab>
        <ng-template mat-tab-label>
           <app-export-menu [disabledButton]="tab.isActive">
           </app-export-menu>
    </mat-tab>

NOTE: By defect a template reference variable makes reference to the "component" or to the "HTMLElement" when we are using a directive. It's the reason the directives has a property: exportAs. When this happens you use the templates reference variable as #myvariable="DirectiveExportAs".

This happens, e.g. when we use ngModel. it's the reason to use

<input [(ngModel)]="variable #myinput="NgModel">

CodePudding user response:

Since mat-tab is exported as matTab

You can Defines the name that can be used in the template to assign this directive to a variable

Then you can read mat-tab isActive property

<mat-tab-group>        
    <div *ngFor="let elem of infosOnglet$ | async">
        <mat-tab  #mT="matTab" isActive>
            <ng-template mat-tab-label>
               <app-export-menu [disabledButton]="mT.isActive">
               </app-export-menu>
        </mat-tab>
    </div>
</mat-tab-group>

CodePudding user response:

if you know limited set of components that this directive is going to be used with, then you can inject them directly and handle them however you like.

class MyDir {
  constructor(@Optional() @Inject(MatTab) private tab: MatTab, @Optional() @Inject(MatSomething) private something MatSomething ) {
   if(![tab, something].some(Boolean)) { throw Error('directive my-dir should be used on MatTab or MatSomething')}
 }
  // you have access to MatTab component in your directive
}
  • Related