Angular2 can dynamically display or conceal a content div based on the value selected in a select box

I am struggling with the issue of hiding and showing a div based on the value selected from a drop-down list. As a newcomer to Angular technology, I attempted using functions without success. I have heard that simply utilizing (ng-model) could achieve this. Can anyone confirm if this approach is viable in this scenario?

app.ts

//our root app component

import {Component, Directive, ElementRef} from 'angular2/core'

@Component({
  selector: 'my-app',
  directives: [],
  providers: [],
  template: `
    <div>
      <h2>Show Hidden{{name}}</h2>
      <label>Choose</label>
      <select [(ngModel)]="productCategory" name="Select name" class="ui fluid search selection dropdown"> 
                  <option value=""></option>
                  <option value = "YES">Yes</option>
                  <option value="NO">No</option>
      </select>
    </div>
    <br><br>
      <div class="row" id="informationDiv" style="display:none">
                <div class="col-md-3 form-group">
                  <label class="control-label">Displaying</label>
                  <input class="form-control" id="productName">
                </div>
      </div>

  `,
  directives: []
})
export class App {


  constructor() {
    setTimeout(() => {
      jQuery('.ui.dropdown').dropdown();
    }, 1000);)
  }
}

My code snippet on Plunker: https://plnkr.co/edit/Mh0yHafi0dmsAynLEQYB?p=preview

Answer №1

I made some updates to the HTML code in your Plunker so that the div element will only display if the name "Paul" is selected:

<div>
      <h2>Greetings, {{name}}!</h2>
      <label>Name</label>
      <select #selectt [(ngModel)]="name" name="Select name" class="ui fluid search selection dropdown"> 
        <option *ngFor="#n of names" [attr.value]="n">{{n}}</option>
      </select>
      <div class="row" id="informationDiv" *ngIf="name === 'Paul'">
                <div class="col-md-3 form-group">
                  <label class="control-label">Displaying:</label>
                  <input class="form-control" id="productName"  [(ngModel)]=name>
                </div>
      </div>
    </div>

Additionally, I have updated the input field with id "productName" to be bound to the selected value.

Answer №2

To see the updated version, visit this link on plnkr: https://plnkr.co/edit/Mh0yHafi0dmsAynLEQYB?p=preview

Simply include [(ngModel)] and *ngIf in the following way:

<div>
      <h2>Show Hidden{{name}}</h2>
      <label>Choose</label>
      <select id="me" [(ngModel)]="chosenValue" class="ui fluid search selection dropdown"> 
                  <option value=""></option>
                  <option value = "YES">Yes</option>
                  <option value="NO">No</option>
      </select>
    </div>
    <br><br>
      <div *ngIf="chosenValue==='YES'" class="row" id="informationDiv">
                <div class="col-md-3 form-group">
                  <label class="control-label">showing</label>
                  <input class="form-control" id="productName">
                </div>
      </div>

Also, don't forget to declare chosenValue in your TS file:

  chosenValue;

Answer №3

Include a new attribute named productCategory in your component class to hold the value of [(ngModel)], then utilize *ngIf for toggling the visibility of the div as shown below

export class App {
  name: string = "Ringo";
  names: string[] = ["John", "Paul", "George", "Ringo"]
  productCategory:string = "";
  constructor() {
    setTimeout(() => {
      jQuery('.ui.dropdown').dropdown();
    }, 1000);)
  }
}




@Component({
  selector: 'my-app',
  directives: [],
  providers: [],
  template: `
    <div>
      <h2>Show Hidden {{name}}</h2>
      <label>Choose</label>
      <select [(ngModel)]="productCategory" name="Select name" class="ui fluid search selection dropdown"> 
                  <option value=""></option>
                  <option value = "YES">Yes</option>
                  <option value="NO">No</option>
      </select>
    </div>
    <br><br>
      <div class="row" id="informationDiv" *ngIf="productCategory == 'YES'">
                <div class="col-md-3 form-group">
                  <label class="control-label">showing</label>
                  <input class="form-control" id="productName">
                </div>
      </div>
  `,
  directives: []
})

Access an updated plunker through the link provided, dependent on the selectbox's value

https://plnkr.co/edit/TMoXrf3VWdjYGXFoJLnf?p=preview

Answer №4

Take a look at this recommendation: [ngIf directive][1]

[1]: .

Incorporate a click function into the dropdown menu. Assign a value in the typescript file and retrieve the value in the html. Utilize that value for the ngIf condition. For example ==>

<div *ngIf="value==yes">
</div>

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

Creating a new bookmark in Firefox without encountering a pop-up dialog box

I am curious if it is feasible to utilize JavaScript to add a bookmark in Firefox seamlessly, without triggering any dialog box. Essentially, can I have the user click on a link and have the bookmark generated automatically, bypassing any additional step ...

Rails: Generating HTML output straight from the controller

Looking for some guidance on handling the response from an AJAX call. Here's what I'm trying to achieve: Initiate an AJAX call to my Rails application to retrieve an HTML document. In the Rails controller, access the HTML document stored on dis ...

Having trouble with less.modifyVars not functioning properly in Visual Studio?

I attempted to dynamically change the LESS variable using HTML within an AngularJS function. The code worked fine on XAMPP with simple HTML and CSS, but when I transferred it to an enterprise app in Visual Studio, it stopped functioning properly. While the ...

What is the best way to conceal a child element within a hidden tab using jQuery, ensuring it remains hidden until I choose to reveal it?

Let me provide an example to explain this situation: <div id="panel-1"> <input name="a" type="text" /> <input name="b" type="text" /> <input name="c" type="text" /> <div> <div id="panel-2"> <input name="d" ty ...

Display the actual runtime hyperlink while utilizing the asp tag helper

Whenever I use asp-tag helpers to create a hyperlink, the result is displayed like this: <a asp-page="/demo">Demo</a> The actual html output looks like this: <a href="/test/Demo">Demo</a> However, instead of displaying "Demo" to ...

Customizing the scroll bar hue on Safari for Lion operating system (OS X 10.7)

In Lion, the new scrollbars in Safari change color based on the background color of the body element. Is there a way to manually control whether the scrollbar is dark or light? I am aware of webkit CSS options to style the scrollbar that existed before t ...

Attempting to ensure that the Ajax Form submission occurs only after passing through jQuery validation

I am struggling to make my Ajax form submit only after the jQuery validation function has been completed. Below is the code I have been working with... http://jsfiddle.net/gbaH7/16/ The validation plugin that I have used can be found at ...

Integrate Angular 2 components into WebStorm

I am currently working on a project using Angular 2 (rc5) and TypeScript (1.8.10). Angular 2 is built with TypeScript, but in the node_modules directory, I notice that there are JavaScript files (*.js) along with declaration files (*.d.ts). It makes it di ...

Utilizing Z-Index with Fixed Positioning and Transitions in CSS

Currently in the process of setting up a fresh portfolio website and utilizing the Onepage Scroll Plugin created by Pete R. Recently, I included a fixed navigation bar and now aiming to have elements within a slide overlapping this navigation. Here's ...

Error encountered: wkhtmltopdf Timeout Issue

I have a unique application that allows users to generate PDFs from HTML using a node server. This application utilizes the wkhtmltopdf 0.12.3-dev-79ff51e engine (with patched qt) integrated with node-wkhtmltopdf module. Occasionally, an error message po ...

Headers cannot be set once they have been sent to the client. The source of the second response is unclear at the moment, but it may be related to

After researching extensively on this topic, I have not found a solution to my issue. My setup consists of an API using NodeJS, ExpressJS, and Mongoose, while the frontend is built with ReactJS. When attempting to save data from a form, I encounter the men ...

Unlocking the potential of the ‘Rx Observable’ in Angular 2 to effectively tackle double click issues

let button = document.querySelector('.mbtn'); let lab = document.querySelector('.mlab'); let clickStream = Observable.fromEvent(button,'click'); let doubleClickStream = clickStream .buffer(()=> clickStream.thrott ...

Form validation with JQuery is malfunctioning on browsers used for development

Hello there. I am relatively new to the world of JavaScript and JQuery, and I am currently attempting to implement form validation using JQuery on certain form fields. I have created a conditional statement that checks if the FULL NAME field is empty or c ...

Is it possible for Bootstrap 5 to extract data from an excel sheet and showcase it in an HTML table?

I have been scouring the depths of the internet with no success in finding a straightforward solution. I recently put together an HTML page that makes use of Bootstrap tables. Currently, my table contents are hardcoded directly into the HTML. I received a ...

Tips on stopping Firefox from automatically scrolling to the bottom of the page when a large popup appears

One of the challenges I'm encountering in my application is that, when using a simple onClick event to show a popup with a large size, the page automatically scrolls down to the bottom after the popup appears. This issue seems to be specific to the Fi ...

HTML page filled to the brim with data tables

Wrapping up a midterm assignment for an HTML course and facing an issue on the final page. The table is overflowing to the right when the browser isn't maximized, and I'm stumped on how to solve it. Any suggestions? Unfortunately, unable to shar ...

The images in the React slick carousel appear to be slightly out of

I'm experiencing blurriness in my carousel when it animates with card items. Despite searching for a solution, I haven't found one yet. My tech stack includes Next.js and TypeScript. const ref = useRef<any>(); const settings = { arro ...

Exploring iPhone Safari Web App: Discovering functions tailored for iPhone users

I am exploring the possibilities of accessing native iPhone features while developing a Web App using html/css/javascript and running it in Safari. I am curious to know if I can tap into smartphone-specific features, especially those unique to iPhone/iTou ...

MongoDB does not recognize Db.Collection as a valid function

A lot of people have been inquiring about this specific error, but after thorough investigation, I couldn't pinpoint a similar issue. So I'm reaching out in the hopes that someone might be able to identify and help rectify it. Let me provide som ...

"Consolidating data from various tables into a single, time-ordered feed using Rails

Asking for advice: managing 2 tables - Posts & Websites. It's a challenge to ensure a single feed displays both posts and websites in chronological order. Any suggestions on how to achieve this seamlessly? Currently, I retrieve data separately: Post ...