Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 access parent DOM element attribute

Tags:

angular

How do I access [attr.open]="false" from the div "child_div". In short I want to emulate the code sample below, but I don't know how to access parent attr from child div.

<div class="parent_div" *ngFor="let level_1 of [1,2,3]" [attr.open]="false">
   <div class="chlid_div" *ngIf="parent.attr.open">

       <div class="parent_div" *ngFor="let level_2 of [1,2,3]"
       [attr.open]="false">
          <div class="chlid_div" *ngIf="parent.attr.open">
             content
          </div>
       </div>

   </div>
</div>
like image 404
yodalr Avatar asked Sep 20 '26 17:09

yodalr


2 Answers

You can make use of the Following Template

<div [attr.open]="my()">
   <div class="chlid_div" *ngIf="data">content</div>
</div>

Component

export class AppComponent {
  data: boolean;


  my() {
    this.data = true;
  }

}

Working Example

like image 178
Rahul Singh Avatar answered Sep 23 '26 07:09

Rahul Singh


Ok the solution was actually pretty simple, no directives or editing in component needed, pure template solution.

<div #areaLevel class="parent_div" *ngFor="let level_1 of [1,2,3]">
   <div class="chlid_div" [hidden]="areaLevel.expanded">

        <div class="button" [class.closed]="areaLevel.expanded" (click)="areaLevel.expanded = !areaLevel.expanded">
            +
        </div>

       <div #areaLevel class="parent_div" *ngFor="let level_2 of [1,2,3]">
          <div class="chlid_div" [hidden]="areaLevel.expanded">
             ...this can continue indefenitly...
          </div>
       </div>

   </div>
</div>

You can use either *ngIf or [hidden], like I did, but with *ngIf it destroys the DOM and if you open it again it builds it from 0.

like image 20
yodalr Avatar answered Sep 23 '26 07:09

yodalr