2

There are more than two template variables in my component, just like blow:

<div #div1>
    <div #part1 [hidden]="true">
    </div>
    <div #part2>
    </div>
</div>
<div #div2>
    <div #part3 [hidden]="true">
    </div>
    <div #part4>
    </div>
 </div>
<button (click)="showDiv(div1,div2)"></button>

I wanna click the button to show part1 and hide part2, same as part3 and part4, but it's just one button, what I can do now is to replace the div1 and div2 with part1 and part2, then what about part3 and part4? Another button? But the real request is more than two divs, maybe a dozen, so, can anyone help? Thanks a lot.

Hal Shaw
  • 25
  • 6

2 Answers2

0

Inside your component you can add something like this

`

constructor(private renderer: Renderer2, private el: ElementRef) {}
showDiv(){
this.renderer.setStyle(
    this.el.nativeElement,
    'display:None',
    'block'
  );
}

`

0

To solve your issue, you could use ngContainer and ngTemplate.

Using ngContainer and ngTemplate:

HTML:

<div> <!-- Div 1 -->
  <ng-container *ngIf="isPartVisible(1); then part1; else part2"></ng-container> 
  <ng-template #part1><div>Part 1</div></ng-template>
  <ng-template #part2><div>Part 2</div></ng-template>
</div>
<!-- Other parts here. -->

JavaScript:

var partVisibilities = {};
partVisibilities["1"] = true;

public isPartVisible(part) {
    return partVisiblities[part] == true; 
    // If you haven't set the visibility setting for a part yet, then it will not show as undefined is falsy in JS.
}
ACOMIT001
  • 510
  • 1
  • 7
  • 21