implementing dynamic visibility with ngIf directive in Angular

header.component.html

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a href="#" class="navbar-brand">Recipe Book</a>
    </div>

    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li><a href="#" (click)="onReceipeList()">Recipes</a></li>
        <li><a href="#" (click)="onShoppingList()">Shopping List</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" role="button">Manage <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Save Data</a></li>
            <li><a href="#">Fetch Data</a></li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</nav>

header.component.ts

import { Component, Output } from '@angular/core';
import { EventEmitter } from 'events';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html'
})


export class HeaderComponent {
  // triggering the methods 
  @Output()receipeClick=true;
  @Output()shoppingClick=true;

  onReceipeList(){
    console.log("we are inside Receipe List")
    this.receipeClick=false;
  }

  onShoppingList(){
    console.log("we are inside shooping click")
    this.shoppingClick=false;
  }
}

app-component.html

<app-header></app-header>
<div class="container">
  <div class="row>
    <div class="col-md-12 ¨>
      <app-recipes *ngIf="!receipeClick"></app-recipes>
      <app-shopping-list *ngIf="!shoppingClick"></app-shopping-list>
    </div>
  </div>
</div>

1)I need to render my code conditionally.

2)Whenever a user clicks the header component, I have an event listener that triggers a method which changes the boolean value in my code and exports it as output.

3)This change in expression is then listened to by the list component.

However, my code isn't working and I'm unsure of why.

Answer №1

There seems to be no requirement to declare Output properties in this case:

@Output()receipeClick=true;
@Output()shoppingClick=true;

Since they are simply used as variables, you can simplify it to:

receipeClick = true;
shoppingClick = true;

Answer №2

index.html

<app-header (menuClick)="updateMenuState($event)">
</app-header>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <app-menu *ngIf="!menuClick"></app-menu>
      <app-sidebar *ngIf="!sidebarClick"></app-sidebar>
    </div>
  </div>
</div>

app.component.ts

menuClick = true;
sidebarClick = true;

updateMenuState(val) {
    this.menuClick = val;
}
updateSidebarState(val) {
    this.sidebarClick = val;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the hidden gems of npm package.json: the keys

There are some keys in the package.json file of Angular 2/4's source code that remain undocumented: { "name": "@angular/platform-browser/animations", "typings": "../animations.d.ts", "main": "../bundles/platform-browser-animations.umd.js", "m ...

The contenteditable DIV function is experiencing issues with Angular's two-way binding feature in the Firefox browser

After making my div contenteditable and triggering ngx-popover on keyup to display search results based on searchText, I am in need of two-way binding along with content editability. However, I prefer using a div instead of an input element: <span> ...

Exploring Reactive Programming with RxJS and organizing data into individual streams

As I delve deeper into working reactively with Angular 15 and RxJS observables for a UI component, my focus lies on subscribing to data solely within the component template (html). The data is fetched from an external system through a service. However, a c ...

What is the best way to guarantee that an object contains certain fields using Partial<>?

I am dealing with a function that accepts a parameter as shown below: const handleAccount = ( account: Partial<IAccountDocument>, ... ) => { ... } It is crucial that the interface for IAccountDocument cannot be modified to avoid requiring cer ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

What is the best way to retrieve a cookie sent from the server on a subdomain's domain within the client request headers using getServerSideProps

Currently, I have an express application using express-session running on my server hosted at api.example.com, along with a NextJS application hosted at example.com. While everything functions smoothly locally with the server setting a cookie that can be r ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

Align and resize image using CSS styling

Seeking assistance on centering and cropping images using CSS. Tried implementing the technique from this specific article. However, experiencing inconsistencies in device UI output. Can someone shed light on this behavior? Scenario: The objective is t ...

Exploring Angular Unit Testing: A Beginner's Guide to Running a Simple Test

I'm diving into the world of angular unit testing and looking to set up my first successful test. Here's what I've come up with: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AppComponent } fro ...

Typescript provides the flexibility to construct incomplete or partially valid objects

My attempt to create a partial helper function in Typescript led me to an incorrect version that went unnoticed by Typescript: Typescript version: 5.2.2 type A = { a: number; b: string }; // incorrect const buildPartialBad = (key: keyof A, val: A[keyof A ...

Utilizing a directive for dynamically applying classes to the host element

Exploring the world of Angular 2 has been quite interesting. I recently grasped the concept of using the Angular Renderer to manipulate ElementStyle, and now I am eager to dive into the Renderer method: setElementClass(renderElement: any, className: strin ...

In order to address the issue of displaying a 404 error in In-Memory Angular,

I have watched all the videos regarding the In-memory web API and diligently followed all the steps and instructions. However, I am still encountering a 404 Error. Please inform me if I missed something or made an error. I have attempted to troubleshoot an ...

Utilizing Angular 2 in a MEAN application, and configuring the systemjs.config.js to serve the node_modules folder

Do you think it is a good idea to serve the "node_modules" folder as static to the front-end? In my Angular 4 app, I am using systemjs.config.js file to load dependency modules like core-js and reflect-metadata to bootstrap the application and load the mai ...

Combining several JSON objects into a single JSON object using JavaScript

I am in need of merging JSON objects from various sources into a single JSON object using JavaScript. For example, I have two JSON objects with different values that I need to combine and add a new value to the final result. json1= { "b":"t ...

Steps to deactivate two choices in a multi-select dropdown menu and visually dim those options

Hey there, I recently worked with Angular8 and Bootstrap 4. I utilized a Bootstrap multi-select dropdown, where I encountered an issue: specifically, I'm trying to disable and gray out the options for PL Marketing and CL Marketing but have been unsucc ...

Capacitor-enabled Ionic Audio Recording

Finally completed my chat app, but I am looking to enhance the voice messaging feature to be more in line with Messenger rather than a standard file.wav format. Any suggestions or ideas would be greatly appreciated! https://i.stack.imgur.com/soXZC.png Cu ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

I encountered an unexpected obstacle while reloading my Next.js application with animejs. The error message reads: "SyntaxError: Unexpected token 'export'." This unwelcome occurrence took place during the

Encountering an error with animejs when reloading my Next.js app: An unexpected token 'export' is causing a SyntaxError. This issue occurred during the page generation process. The error originates from file:///Users/.../node_modules/animejs/lib ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Deciphering Route Parameters within Angular 2

Recently diving into Angular 2, I stumbled upon this resource, which details various methods for creating route links. 1. <a [routerLink]="[ '/path', routeParam ]"> 2. <a [routerLink]="[ '/path', { matrixParam: 'value&ap ...