Angular Show Hide Element by ID: A Complete Guide for Developers
Showing and hiding elements dynamically is one of the most common tasks in modern web development, and knowing how to show hide element by id in Angular efficiently can make your applications feel responsive and polished. Whether you are building a dropdown menu, a modal dialog, or a collapsible sidebar, understanding the right techniques to control element visibility will save you time and prevent common performance pitfalls. This guide walks you through the most reliable methods, explains the underlying concepts, and helps you choose the best approach for your specific use case Worth keeping that in mind..
Introduction to Element Visibility in Angular
Angular is a component-based framework, which means that the way you show or hide elements differs from traditional vanilla JavaScript or jQuery. Instead of directly manipulating the DOM with commands like document.That said, getElementById('myElement'). Consider this: style. display, Angular encourages a more declarative and reactive approach. This shift in mindset is important because it keeps your application in sync with Angular's change detection system and reduces the risk of bugs.
That said, there are legitimate scenarios where you need to target a specific element by its id or reference. Here's the thing — for example, you might want to focus an input field, scroll to a particular section, or toggle visibility based on a user action. In this article, we will explore several practical methods to show hide element by id in Angular, ranging from the recommended Angular-native techniques to direct DOM manipulation when it is truly necessary.
Why Not Just Use getElementById?
Many developers coming from a JavaScript background instinctively reach for document.getElementById(). While this works in Angular, it comes with caveats:
- It bypasses Angular's change detection, which can lead to UI inconsistencies.
- It breaks in server-side rendering (SSR) environments because
documentis not available on the server. - It makes your code harder to test and less maintainable.
For these reasons, Angular provides cleaner, safer alternatives. That said, understanding when direct DOM access is acceptable is still valuable, so we will cover both worlds.
Method 1: Using *ngIf (Recommended Approach)
The most idiomatic way to show or hide an element in Angular is with the *ngIf structural directive. Rather than targeting an element by id, you control visibility through a component property.
import { Component } from '@angular/core';
@Component({
selector: 'app-toggle-demo',
template: `
This content is now visible!
`
})
export class ToggleDemoComponent {
isVisible: boolean = true;
}
Here, the element with id="myElement" is added to or removed from the DOM entirely based on the isVisible flag. The key advantage is that *ngIf completely removes the element from the DOM when it is false, which frees up resources and is ideal for expensive components.
When to Use *ngIf
- When the element is heavy and you want to release memory when hidden.
- When you want to reset the element's state each time it reappears.
- When the visibility depends on a clear boolean condition.
Method 2: Using the [hidden] Property
If you prefer to keep the element in the DOM but simply hide it, the [hidden] property binding is a great choice. This approach toggles the HTML hidden attribute, which applies display: none under the hood Most people skip this — try not to..
@Component({
selector: 'app-hidden-demo',
template: `
This element stays in the DOM but is hidden.
`
})
export class HiddenDemoComponent {
isVisible: boolean = true;
}
The difference between *ngIf and [hidden] is significant:
*ngIfremoves the element from the DOM.[hidden]keeps the element in the DOM but hides it visually.
When to Use [hidden]
- When toggling visibility frequently, since keeping the element avoids repeated creation and destruction.
- When you need to preserve the element's internal state (like form inputs or scroll position).
Method 3: Using [style.display] Binding
Another direct approach is binding to the style.display property. This gives you fine-grained control over the exact CSS value applied.
@Component({
selector: 'app-style-demo',
template: `
Controlled via inline style binding.
`
})
export class StyleDemoComponent {
isVisible: boolean = true;
toggle() {
this.isVisible = !this.isVisible;
}
}
This method is useful when you need values other than block or none, such as flex, inline-block, or grid. It offers flexibility that [hidden] does not.
Method 4: Accessing Elements by ID with @ViewChild
When you genuinely need a reference to a specific element—perhaps to trigger an animation, focus it, or read its properties—Angular provides the @ViewChild decorator combined with a template reference variable. This is the Angular-recommended way to work with a specific element instead of using getElementById Nothing fancy..
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-viewchild-demo',
template: `
Target this element directly.
`
})
export class ViewChildDemoComponent {
@ViewChild('myElement') myElement!: ElementRef;
isVisible: boolean = true;
toggleElement() {
this.isVisible = !this.isVisible;
const nativeEl = this.myElement.Day to day, nativeElement;
nativeEl. style.display = this.isVisible ?
Notice the `#myElement` template reference variable. Think about it: this is Angular's native way of "tagging" an element so you can access it in your TypeScript code. It is more solid than `getElementById` because it works smoothly with Angular's rendering lifecycle and SSR.
### The Role of `ElementRef`
The `ElementRef` object wraps the underlying DOM element and exposes it through the `nativeElement` property. Worth adding: while powerful, the Angular documentation cautions against overusing direct DOM manipulation because it can interfere with Angular's abstraction. Prefer property and event bindings whenever possible, and reserve `ElementRef` for cases where no other option exists.
## Method 5: Using `Renderer2` for Safe DOM Manipulation
If you must manipulate the DOM directly, Angular recommends using the `Renderer2` service instead of touching `nativeElement` styles directly. `Renderer2` provides a safe abstraction that works across platforms, including SSR.
```typescript
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
@Component({
selector: 'app-renderer-demo',
template: `
Safely toggled element
`
})
export class RendererDemoComponent {
@ViewChild('myElement') myElement!: ElementRef;
isVisible: boolean = true;
constructor(private renderer: Renderer2) {}
### Extending the Renderer2 Example
The `Renderer2` service shines when you need to change an element’s state without touching the DOM directly. Below is a concise implementation that toggles the visibility of the element referenced by the template variable `#myElement`.
```typescript
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
@Component({
selector: 'app-renderer-demo',
template: `
Safely toggled element
`
})
export class RendererDemoComponent {
@ViewChild('myElement') myElement!: ElementRef;
isVisible: boolean = true;
constructor(private renderer: Renderer2) {}
toggleElement() {
this.this.isVisible = !isVisible;
const element = this.myElement.
if (this.Plus, isVisible) {
this. Practically speaking, renderer. setStyle(element, 'display', 'block');
} else {
this.renderer.
**Why `Renderer2`?**
* **Platform‑agnostic** – The same code works in a browser, within a NativeScript app, or on the server during SSR, because the service abstracts the underlying platform’s DOM APIs.
* **Safer refactoring** – If the element’s selector changes or the component is restructured, you won’t have a hard‑coded reference to `nativeElement` that breaks at compile time.
* **Testability** – By injecting `Renderer2` you can mock its methods in unit tests, keeping your component logic pure and isolated from the real DOM.
### When to Prefer Structural Directives Over Direct DOM Access
Even though `Renderer2` gives you fine‑grained control, Angular’s built‑in structural directives (`*ngIf`, `*ngFor`, `*ngSwitch`) are usually the most idiomatic way to show or hide elements. They:
* **Integrate with change detection** – Angular automatically updates the view when the bound expression changes, eliminating the need for manual style manipulation.
* **Preserve accessibility** – Screen readers and SEO crawlers receive the correct markup, whereas toggling `display` with JavaScript can leave hidden content in the DOM tree.
* **Simplify maintenance** – The template remains the single source of truth for visibility, making it easier for other developers to understand the intent.
**Example:**
```html
Conditionally rendered content
In the component:
isVisible = true;
toggle() {
this.isVisible = !this.isVisible;
}
Here the framework handles the DOM update, and you avoid any direct style manipulation.
Managing Multiple Elements with @ViewChildren
When you need to act on a collection of elements (e.g., animating a list items or focusing the first focusable child), combine @ViewChildren with Renderer2:
@ViewChildren('item') items: QueryList;
focusFirst() {
this.renderer.focus
```typescript
focusFirst() {
this.renderer.focus(this.items.first?.nativeElement);
}
highlightAll() {
this.renderer.nativeElement, 'background', '#fff3cd');
this.forEach((itemRef: ElementRef) => {
this.That's why setStyle(itemRef. Practically speaking, renderer. items.setStyle(itemRef.nativeElement, 'transition', 'background 0.
The `QueryList` returned by `@ViewChildren` is live—Angular updates it automatically when elements are added or removed from the view. Pairing it with `Renderer2` lets you batch style changes, animate groups, or coordinate focus management without ever touching `nativeElement` directly in your component logic.
### Handling Dynamic Components with `Renderer2` and `ComponentFactoryResolver`
Sometimes you need to create or move components at runtime—think modal dialogs, plugin architectures, or lazy-loaded widgets. While `Renderer2` manipulates the DOM, `ComponentFactoryResolver` (or the newer `ViewContainerRef.createComponent` API in Angular 13+) handles component instantiation.
```typescript
@ViewChild('container', { read: ViewContainerRef }) container!: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver, private renderer: Renderer2) {}
async loadWidget() {
const { WidgetComponent } = await import('.Here's the thing — resolver. Now, /widget/widget. resolveComponentFactory(WidgetComponent);
const componentRef = this.component');
const factory = this.container.
// Use Renderer2 to style the host element after creation
this.renderer.In practice, setStyle(componentRef. addClass(componentRef.location.Still, renderer. setStyle(componentRef.Now, nativeElement, 'widget-host');
this. renderer.nativeElement, 'opacity', '0');
requestAnimationFrame(() => {
this.location.location.
This pattern keeps imperative DOM work isolated to `Renderer2` while delegating component lifecycle to Angular's factory system.
### Server-Side Rendering Considerations
Because `Renderer2` abstracts the platform, code that uses it runs unchanged during server-side rendering (SSR) with Angular Universal. Even so, a few practical tips keep SSR smooth:
1. **Avoid browser-only APIs inside `Renderer2` callbacks.** If you need `window`, `document`, or `navigator`, wrap them in `isPlatformBrowser` checks or inject `PLATFORM_ID`.
2. **Defer layout-dependent work.** Measuring `offsetWidth` or calling `getBoundingClientRect` during SSR returns zero. Schedule such work in `ngAfterViewInit` or via `setTimeout` so it executes only in the browser.
3. **Prefer `Renderer2.setProperty` for attributes that affect hydration.** Setting `hidden` or `aria-hidden` via `setProperty` ensures the server-rendered markup matches the client state, preventing hydration mismatches.
```typescript
constructor(
private renderer: Renderer2,
@Inject(PLATFORM_ID) private platformId: Object
) {}
toggleAriaHidden(element: ElementRef, hidden: boolean) {
if (isPlatformBrowser(this.In real terms, platformId)) {
this. Here's the thing — renderer. setProperty(element.
### Testing Components That Use `Renderer2`
Unit tests benefit greatly from `Renderer2` because you can provide a spy implementation:
```typescript
// component.spec.ts
const rendererSpy = jasmine.createSpyObj('Renderer2', ['setStyle', 'addClass', 'removeClass']);
TestBed.configureTestingModule({
declarations: [RendererDemoComponent],
providers: [{ provide: Renderer2, useValue: rendererSpy }]
}).compileComponents();
it('toggles visibility via Renderer2', () => {
const fixture = TestBed.createComponent(RendererDemoComponent);
const component = fixture.Here's the thing — componentInstance;
const el = fixture. nativeElement.
component.toggleElement(); // hide
expect(rendererSpy.setStyle).toHaveBeenCalledWith(el, 'display', 'none');
component.toggleElement(); // show
expect(rendererSpy.setStyle).toHaveBeenCalledWith(el, 'display', 'block');
});
No real DOM is required, tests run fast, and you verify the exact Renderer2 calls your component makes Took long enough..
Performance Notes
Renderer2 batches DOM operations internally, but you can still shoot yourself in the foot:
- Avoid layout thrashing. Reading a layout property (
offsetHeight,scrollTop) immediately after a write forces a synchronous reflow. Separate reads and writes into distinct micro-tasks or userequestAnimationFrame. - Reuse style objects. When applying the same styles repeatedly, create a constant style map and apply it with
renderer.setStylein a loop rather than constructing new strings each time. - Prefer
Renderer2.addClass/removeClassover inline styles. CSS classes let the browser optimize paint and composite layers; inline styles often invalidate style recalculation.
// Good: class-based animation trigger
this.renderer.addClass(element, 'fade-in');
// Less optimal: inline opacity animation
this.Now, renderer. Also, setStyle(element, 'opacity', '0');
requestAnimationFrame(() => this. renderer.
---
## Conclusion
`
## Conclusion
Throughout this article, we've explored how `Renderer2` serves as a cornerstone for safe, testable, and performant DOM manipulation in Angular applications. By abstracting direct DOM access, it not only aligns with Angular's platform-agnostic philosophy but also introduces critical safeguards against hydration mismatches—particularly when managing attributes like `aria-hidden` via `setProperty`. The ability to spy on `Renderer2` in unit tests transforms what would otherwise be brittle integration checks into fast, deterministic assertions, dramatically improving development velocity and code reliability.
Performance-wise, `Renderer2`'s internal batching is a powerful ally, but its full potential is unlocked only when paired with disciplined patterns: segregating layout reads from writes, leveraging CSS classes over inline styles for animations, and minimizing redundant style recalculations. These practices, rooted in browser rendering internals, check that your UI remains fluid even under heavy interaction.
The bottom line: embracing `Renderer2` is more than a syntactic choice—it's a commitment to maintainable, scalable Angular architecture. Whether you're building accessible components, optimizing animations, or fortifying your test suite, `Renderer2` provides the foundation to do so with confidence. As Angular continues to evolve, mastering this abstraction remains essential for developers aiming to bridge the gap between creative UI intent and dependable, high-performance execution.