Tips for toggling visibility in Angular 2

I utilized [hidden] in the following way where the value of "secondTab" is set to true.

<form #siteForm="ngForm" novalidate (ngSubmit)="saveSite(siteForm.value,siteForm.valid)" class="admin-modal">

  <div class="txt-danger">{{errorMessage}}</div><br/>
  <ul role="tablist" class="nav nav-tabs">
    <li [ngClass]="{active:firstTab}"><a (click)="siteDetail()">Site Details</a></li>
    <li [ngClass]="{active:secondTab}"><a (click)="siteLocation()">Site Location</a></li>
  </ul>
  <div [hidden]="secondTab">
    <input type="hidden" class="form-control" value="{{site.location}}" name="location" [(ngModel)]="site.location" #location>
    <input type="hidden" class="form-control" value="{{site.id}}" name="id" [(ngModel)]="site.id" #id>
    <div class="form-group mb-20" [ngClass]="{'has-error':name.errors && (name.dirty || name.touched || siteForm.submitted)}">
      <label class="control-label mb-10">Site Name</label>
      <input type="text" class="form-control default-rounded" name="name" required [(ngModel)]="site.name" #name>
      <small [hidden]="name.valid || (name.pristine && !siteForm.submitted)" class="text-danger">
        Name is required.
      </small>
    </div>  
    <div class="form-group mb-20" [ngClass]="{'has-error':maximumCapacity.errors && (maximumCapacity.dirty || maximumCapacity.touched || siteForm.submitted)}">
      <label class="control-label mb-10">Maximum Capacity</label>
      <input type="text" class="form-control default-rounded" name="maximumCapacity" required [(ngModel)]="site.maximumCapacity" #maximumCapacity pattern="[0-9]+">
      <small [hidden]="maximumCapacity.valid || (maximumCapacity.pristine && !siteForm.submitted)" class="text-danger">
        Maximum capacity is required (enter only digits)
      </small>
    </div>     
    <div class="form-group mb-20">
      <label class="control-label mb-10">Site Type</label>
      <select class="form-control" name="type" [(ngModel)]="site.type" #type>
        <option>Commercial</option>
        <option>Residential</option>
        <option>Industrial</option>
        <option>Etc</option>
      </select>
    </div>
    <div class="form-group mb-20" [ngClass]="{'has-error':contactNumber.errors && (contactNumber.dirty || contactNumber.touched || siteForm.submitted)}">
      <label class="control-label mb-10">Site Contact Number</label>
      <input type="text" class="form-control default-rounded" name="contactNumber" required [(ngModel)]="site.contactNumber" #contactNumber>
      <small [hidden]="contactNumber.valid || (contactNumber.pristine && !siteForm.submitted)" class="text-danger">
        Site contact number is required
      </small>
    </div> 
  </div>
  <div [hidden]="firstTab">
    <div class="form-group mb-20">
      <label class="control-label">Address</label>
      <div class="flex">
        <div class="w-79 mr-10 mt-5">
          <input type="text" class="form-control default-rounded" name="location" required  places-auto-complete (place_changed)="placeChanged($event)" [types]="['geocode']">
        </div>
        <div class="mt-5">
          <button type="button" class="btn btn-primary black-background white-text pull-right" (click)="changeMap()">Lookup</button>
        </div>
      </div>
    </div>
    <div class="form-group mb-20">
      <ng2-map zoom="{{zoom}}" center="{{site.latitude}}, {{site.longitude}}">
        <marker *ngFor="let pos of positions" [position]="pos" [icon]="markerImage"></marker>
        <drawing-manager [drawingMode]="'marker'" [drawingControl]="true" [drawingControlOptions]="{ position: 2, drawingModes: ['marker', 'circle', 'polygon', 'polyline', 'rectangle'] }" [circleOptions]="{ fillColor: '#ffff00', fillOpacity: 1, strokeWeight: 5, editable: true, zIndex: 1 }"></drawing-manager>
      </ng2-map>
    </div>
  </div>

  <button type="submit" class="btn btn-primary black-background white-text pull-right">Save</button>

If I change the value of "secondTab" to false, then I encounter the following error

ORIGINAL EXCEPTION: self._NgModel_202_5.context is not a function

If I use ngFor instead of [hidden], everything runs smoothly but I do not receive the value on form submission when I am on the second tab.

If I utilize formBuilder instead for the form, then it functions correctly. Therefore, the issue may lie with ngModel.

Answer №1

What are the benefits of utilizing this method?

#location="ngModel"

Typically, #variable is used to create a reference to the HTML element in this scenario.

Consider modifying the code to:

<div [hidden]="secondTab">
  <input type="hidden" class="form-control" value="{{site.location}}" name="location" [(ngModel)]="site.location" #location>
</div>

Instead of using the hidden property, it's recommended to use *ngIf="secondTab"

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

Having trouble configuring the routes on my MEAN Stack application

I'm currently working on a basic application using the MEAN stack, but I'm facing issues with my routes. When I access localhost:3000, it redirects me to the 404 error page instead of displaying the posts at localhost:3000/#/home as expected. It ...

Converting JS carousel to TS for showcasing multiple items

I am currently working on integrating a bootstrap carousel into my Angular project and I need to convert my JavaScript file to a TypeScript file. As someone who is new to this, I'm unsure of the process for converting and implementing it in a .ts file ...

Can you explain the functionality of this Sample AngularJS Infinite Scroll feature?

I stumbled upon this AngularJS script while searching for some samples, but I'm having trouble understanding the angular module and directive aspects of the code. However, I did manage to modify the loadMore() function to fetch a JSON resource from my ...

What is the best way to send an observable with parameters through @Input?

The objective is to transfer an http request from Component 1 to Component 2 and initialize its parameters on Component 2. Here is a pseudo code representation of my approach: Component 1 HTML <app-component-2 [obs]="obs"></app-component-1> ...

"AngularJS offers a unique way to include alternative text in placeholders and titles using

I need to implement an input field (<input..>) with a placeholder and title for tooltip that functions in the following way: There is a variable called "myString" which can either be undefined/empty or contain a string. When empty, a default string ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

Encountering an error while implementing a Typescript addEventListener for keydown events

Struggling with adding and removing event listeners to HTML elements capable of focus, such as buttons. encountering a typescript error specifically related to the lines of code responsible for adding and removing the event listener: focusableElements.fo ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

retrieving information from an array nested within a JSON object in an Angular application

I am struggling to retrieve two specific values from a JSON object. The content of the JSON is as follows: [ { "type":"session_start", "properties":[ { "property":"activity&q ...

Is the Prisma model not reachable through Prisma Client?

I'm currently attempting to retrieve a specific property of a Prisma model using Prisma Client. The model in question is related to restaurants and includes a reviews property that also corresponds with a separate Review model. schema.prisma file: // ...

Angular's AsyncValidatorFn is triggered by the onblur event and does not work with keypress events

I'm currently working with the latest version of Angular and I'm attempting to implement a custom validation for checking a code through a RestAPI. The example below is functional, but it doesn't trigger on keypress events; it only activates ...

invoking a method within an express route to retrieve and utilize middleware functions

For my project, I am working on a custom function to handle API request validation. Here is how it looks: export function validateBody(schema: string): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void { return function ...

Is the Kendo Spreadsheet supported in Angular 2?

We are interested in knowing if future releases of Angular2 will include Kendo Spreadsheet or the ability to export data to Excel for the grid. We currently use the Angular1 version and would like to upgrade, so having these features available in Angular2 ...

What is preventing me from utilizing the import syntax to bring in a coffeescript file within typescript?

So here's the deal: I've got a typescript file where I'm importing various other typescript files like this: import ThingAMajig from '../../../libs/stuffs/ThingAMajig'; // a typescript file However, when it comes to importing my ...

Component for logging in with Ionic 2 and authentication service

I am currently working on implementing a basic login feature in my Ionic 2 application. The login functionality involves a login component that displays the login view and then transmits the user's email and password to the authentication service for ...

What is the best way to handle multiple requests to the same URL in Cypress while waiting?

I am currently developing a Cypress test that involves sending multiple requests to the same URL with varying body content. Essentially, the test modifies input values in the user interface, triggering new server requests. The challenge arises when trying ...

Access-Control-Allow-Origin header not being sent by ExpressJS

In the midst of my project, I find myself needing an angular web application to connect with a node/express backend. Despite trying to implement Cors for this purpose, the express server refuses to send the Access-Control-Allow-Origin header. I am perplexe ...

Manipulate classes by adding or removing them on click events in Angular

I am struggling to implement the angular ngClass for adding a class with a click event. Despite calling a function that should change the value of the "isExpandedConectivity" variable when clicking on the "li" element, it doesn't seem to work as expec ...

Managing Users in a Web App with AngularJS, Spring, and Hibernate

Thought-Provoking Inquiry Back-End Strategy In the process of developing the User Management Module for a Web application, I am working with three tables: User, Role, and UserInterce. The user table is connected to the role table in a ManyToMany relations ...

how to implement a collapsed row feature in an angular table row

My table contains collapsed rows with additional 2nd-level information, but not all rows have this data. Is there a way to create a controller that will display a 2nd level collapse row only if the corresponding JSON script includes 2nd level data? ...