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

What are the steps to integrate Laravel and AngularJS?

Exploring the integration of Laravel with AngularJS has lead me to ponder on the most effective way to structure such a project. Should I (A) opt for a single domain where an API is consumed directly from the Laravel project, or (B) have website.com and a ...

What went awry with my Angular form implementation?

I am new to using angular forms and I am attempting to validate an email field, displaying a message if the input is invalid. Although I thought I had done everything correctly, the error message is not appearing. <form name="Login" novalidate> ...

Guide on transferring object between two $states using ui-router

Visit this link for more information Expected Behavior Upon logging in, selecting a Ticker button is expected to trigger the display of matching Tags for that specific Ticker. Actual Results However, upon clicking a Ticker button after logging in, the ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

Creating a PDF export of your grid using Kendo Grid is a straightforward

I've been facing a challenge while trying to export an entire page using Kendo Angular PDF. Everything works smoothly until I add a Kendo Angular Grid onto the page. The problem arises when certain rows go missing and extra blank space appears on some ...

What sets apart client-side authentication from server-side authentication?

While there is Passport available for Node.js, Sattelizer is the choice for AngularJS. I find it challenging to determine when each should be used. What are the unique features of Sattelizer compared to Passport and vice versa? How does JSON Web Tokens im ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

Disregard the instructions upon loading the page

I've implemented a directive to automatically focus on the newest input field added to my page. It works well, but there is one issue - when the page loads, the last input is selected by default. I want to exclude this behavior during page load and in ...

AngularJS: Loading $http Responses in Batches of 5 or Fewer Items

Currently, I am developing a product catalog application using the Ionic Framework. The backend is powered by PHP to fetch products from the database, and AJAX is utilized to display them on the frontend. Everything seems to be functioning well until I att ...

Leverage various models within a single controller in MEAN.IO framework

I am relatively new to the mean stack development. I have created a package called ModelA and also ModelB. Now, I am facing an issue while trying to reference both models in the ModelA controller. Here is an example: File: ModelA.js var ModelA = new Sche ...

Converting retrieved data into table cells through mapping

I'm facing an issue where I need to display specific addresses for each individual in a table row. For simplicity, let's focus on showing the city specifically as described in this code snippet: https://i.stack.imgur.com/bJmsD.png Currently, whe ...

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...

Place three images in the center of a div container

Recently, I've been working on some HTML code that utilizes the Angular Material library: <div layout="row" layout-wrap style="background: yellow; "> <div ng-repeat="pro in Products" > <md-card class="cardProduct" > ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

Implementing Global Value Assignment Post Angular Service Subscription

Is there a way to globally assign a value outside of a method within my app component? This is how my service is structured: import { NumberInput } from '@angular/cdk/coercion'; import { HttpClient } from '@angular/common/http'; import ...

Angular - Monitoring Changes in Variables

I've recently started working with Angular, primarily using VueJS. I'm curious about how to detect when a variable is updated. In my case, the variable is being updated through a DataService. I came across ngOnChanges(), but it seems that it only ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...

Comparison between bo-html and bo-text

As I was going through the documentation for the bindonce directive, a question popped into my head regarding the distinction between bo-html and bo-text. bo-html: This evaluates "markup" and displays it as HTML within the element. bo-text: ...

onkeypress() method not triggering the function

I have a task to prevent users from typing "%" in a textArea, so I implemented the following: However, even after clicking inside the text area, I can still type '%', indicating that my onkeypress function is not working properly or there is an ...