Daniel Stephens
Daniel Stephens

Reputation: 3209

How to make an element dependent on a data attribute in Angular?

I am using Angular 11 and inside a template dom element I am using a conditional [hidden]. Is there any way to make this dependend on an attribute that I set in Javascript via div.setAttribute("data-foo", 1);?

None of the examples below work for me:

<div [hidden]="data-foo"> </div>
<div [hidden]="attr.data-foo"> </div>

Thank you!

Upvotes: 0

Views: 263

Answers (1)

Srijon Chakraborty
Srijon Chakraborty

Reputation: 2154

I think I have 2 solutions for you. You can hide your content or div or other control in angular using this 2 popular ways.
1. Using [style.visibility]="(conditionalboolProperty=== true) ? 'hidden' : 'visible'"
2. Most Popular one is using *ngIf="conditionalboolProperty"

Here is the full code given below.
TS

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Show and hide en elenment angular';
conditionalboolProperty: boolean = false;
}

HTML:

<div>
  <p>Show </p>
  <div [style.visibility]="(conditionalboolProperty === false) ? 'hidden' : 'visible' ">
     <h1>Condition True</h1>
  </div>
  <p>Hidden </p>
  <div [style.visibility]="(conditionalboolProperty === true) ? 'hidden' : 'visible'">
      <h1>Condition False</h1>
  </div>

  <p>Hidden Using ngIF </p>
  <div *ngIf="conditionalboolProperty">
    <h1>ngIF Condition Show Hide</h1>
  </div>
</div>

Note: Please check the code here Stackblitz

Upvotes: 2

Related Questions