简体   繁体   中英

Angular ngIf can't access parent property

I'm using Angular 5 and Material 5:

<mat-tab-group>
    <mat-tab label="INFO">
        info goes here
    </mat-tab>
    <mat-tab label="CONTACTS">
        <div *ngIf="isActive">
            contacts should load here
        </div>
    </mat-tab>
</mat-tab-group>

I'm trying to show contacts, but only if tab is active. There is isActive property for mat-tab ( https://github.com/angular/material2/blob/5.2.x/src/lib/tabs/tab.ts#L83 ), but I can't access it, it looks undefined.

I can't understand what am I doing wrong.

(I also can't use newer version of Angular at the moment).

This way it works:

<mat-tab-group>
    <mat-tab label="INFO">
        info goes here
    </mat-tab>
    <mat-tab #contactsTab label="CONTACTS">
        <div *ngIf="contactsTab.isActive">
            contacts should load here
        </div>
    </mat-tab>
</mat-tab-group>

Elements can't access the property of any element without a reference to it ( Docs: Components Interactions ) the div isn't treated as a part of mat-tab unless it's a part of it's template, even if it's inside it.

I do not think you need the *ngIf . If you inspect the tab body you should not see content in the inactive tabs.

For example, from this simple StackBlitz , there are two tabs and the second <mat-tab-body> has nothing inside.

Then, click the other tab and the reverse happens.

Source

<mat-tab-group>
  <mat-tab label="One">
    <h1>Some tab content</h1>
    <p>...One</p>
  </mat-tab>
  <mat-tab label="Two">
    <h1>Some more tab content</h1>
    <p>...Two</p>
  </mat-tab>
</mat-tab-group>

DOM inspection, tab 1 is active

<div class="mat-tab-body-wrapper">
  <!--bindings={
    "ng-reflect-ng-for-of": "[object Object],[object Object"
    }-->

  <mat-tab-body class="mat-tab-body ng-tns-c5-0 mat-tab-body-active ng-star-inserted" role="tabpanel" ng-reflect-_content="[object Object]" ng-reflect-position="0" id="mat-tab-content-0-0" aria-labelledby="mat-tab-label-0-0" ng-reflect-origin="0">
    <div class="mat-tab-body-content ng-trigger ng-trigger-translateTab" style="transform: none;">
      <!---->
      <h1 class="ng-star-inserted" style="">Some tab content</h1>
      <p class="ng-star-inserted" style="">...One</p>
      <!---->
    </div>
  </mat-tab-body>

  <mat-tab-body class="mat-tab-body ng-tns-c5-1 ng-star-inserted" role="tabpanel" ng-reflect-_content="[object Object]" ng-reflect-position="1" id="mat-tab-content-0-1" aria-labelledby="mat-tab-label-0-1">
    <div class="mat-tab-body-content ng-trigger ng-trigger-translateTab" style="transform: translate3d(100%, 0px, 0px);">
      <!---->
    </div>
  </mat-tab-body>

</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM