简体   繁体   中英

How to hide element with style in angular

I'm new in angular and I want to make something like:

document.getElementById('div').style.display = 'none';

but I have an error enter image description here

I already deleted the ? mark and still not working its a click event that I want to make to add some animation to it

I think you can try this solution

showModal() {
 const div = document.getElementById('modal');
 if(div) {
   div.style.display = 'none'
 }
}

You need to use ngClass or ngStyle to apply classes or styles conditionally! Avoid the javascript implementation, because further down the development road it will lead to complexity with this implementation! Use Angular standard building items.

ngClass Stackblitz

ngStyle Stackblitz

tutorial

You can show and hide elements using the *ngIf structural directive. You pass it a property that should have a true/false value to determine if the element should be shown or hidden. The following example shows its usage and toggling whether or not to show or hide the modal.

@Component({
  selector: 'my-component',
  template: `
    <div class="modal" *ngIf="hideModal">This is a modal</div>
    <button (click)="toggleModal()">Toggle Modal</button>
  `
})
export class MyComponent implements OnInit {
  hideModal = true;

  toggleModal() {
    this.hideModal = !this.hideModal;
  }
}

I think the equivalent for your example is:

<some-element [ngStyle]="{'display': none}"></some-element>

But you can set a class in your css\less\scss:

.hide { disply: none; }

and use ngClass with some condition:

<some-element [ngClass]="{'hide' : yourCondition}"></some-element>

If you need to do this from your .ts file you can import renderer2 and:

import {  Renderer2, ElementRef } from '@angular/core';

constructor(private renderer: Renderer2) {}

this.renderer.addClass(yourElement, 'hide');

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