Having trouble displaying the button upon initial load using ngIf

My goal is to display a button when editing an input form. Initially, the button is hidden when the page loads but it should appear once any of the input fields are edited. I have also implemented highlighting for the input box that is being edited. However, whenever I try to edit my input field, I encounter an error message saying "NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'". Despite this error, the button does not appear. Strangely, clicking on a random location in the browser makes the button visible. Can someone help me identify the issue here?

In my TypeScript file:

button: boolean;

ngOnInit(): void {
    this.button = false;
}

highlight(input: string): string {
    // logic for coloring...
    if (input.dirty) {
        // change color and show button
        this.button= true;
    }
    return color;
}

In my HTML file:


<button *ngIf="button" label='Submit'>

Answer №1

If you're facing an issue, I suggest trying a different approach that is also demonstrated in my own StackBlitz example:

  • Show a button when at least one form-field has input.
  • Highlight every input-field with input.

The CSS File

Create custom styling for input-fields with input using CSS. The trick involves creating an empty placeholder for the number field and hiding it to indicate input:

input:not(:placeholder-shown) {
  border: 3px dashed yellow;
}

The TS File

Subscribe to form changes and display the button if at least one field has a value. The incoming `res` object contains all form properties and values:

myform: FormGroup;
showButton = false;

ngOnInit() {
  this.myform = new FormGroup({
    numbers: new FormControl(null),
    otherNumbers: new FormControl(null),
  });

  // Subscribe to form changes and show button if any field is not empty:

  this.myform.valueChanges.subscribe((res) => {
    let showBtn = false;
    for (const property in res) {
      showBtn = !!res[property] ? true : showBtn;
    }
    this.showButton = showBtn;
  });
}

The HTML File

Remember to include a placeholder with an empty space for the styling trick to work:

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-md-offset-2 col-sm-offset-1">
      <form [formGroup]="myform">
        <td>
          <input
            type="number"
            pInputText
            class="form-control"
            formControlName="numbers"
            placeholder=" "
          />
        </td>
        <br />
        <td>
          <input
            type="number"
            pInputText
            class="form-control"
            formControlName="otherNumbers"
            placeholder=" "
          />
        </td>
      </form>
    </div>
    <button *ngIf="showButton" label="Submit">Button</button>
  </div>
</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

Equalizing Lists in Angular 2

Struggling to locate documentation on this topic, but in Angular 1 it was possible to achieve the following: <textarea ng-model="name" ng-list=","></textarea> With this setup, if you were to input "Hello, world!" into the textarea, the name v ...

Guide on invoking a private function in Angular2 using RxJS Observables

Greetings, I am a beginner to RxJs and just started learning it today. As a newbie, I have a question regarding its usage. My current task involves extracting XML RSS feed and then converting it into a JSON format. To achieve this, I created a FeedService ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...

Why is passing data:{} to a route essential for achieving the desired outcome?

Check out the Angular Material Documentation Site passing {} to the Homepage route: {path: '', component: HomePage, pathMatch: 'full', data: {}} I'm interested in knowing the significance of data: {}. Recent Discovery Closer ex ...

React component state remains static despite user input

I am currently in the process of developing a basic login/signup form using React, Typescript (which is new to me), and AntDesign. Below is the code for my component: import React, { Component } from 'react' import { Typography, Form, Input, But ...

Mapping URLs to objects in JavaScript, TypeScript, and Angular4

I have implemented a class called SearchFilter class SearchFilter { constructor(bucket: string, pin: number, qty: number, category: string) { } } When the user performs a search, I populate the filter i ...

Fixing the Unspecified addEventListener ErrorLearn how to resolve this error

Having recently started working with Angular, I encountered an issue with my addEventListener method not functioning as intended. My goal is to create a delete button that removes a specific array from my input. This array is nested within a mat-card tag a ...

What is the best way to assign values to multiple form elements simultaneously?

My FormBuilder-built form contains numerous control elements, and I am seeking a more efficient method to set their values based on server responses. Currently, I am handling it in the following manner: this.form.controls['a'].setValue(data.a); ...

Angular 2 Mastering the Art of Saving State in Routing with Precision

I have been working on a search page that retains users' search criteria even after navigating away from the page. I came across a helpful resource at that enabled me to achieve this functionality successfully. However, I encountered an issue where ...

Image control failing to display SVG file

I am facing an issue with displaying an SVG file on the img control in angular10. When I try to use SVG, it's not showing up but it works fine when I change the file type to jpg for the same control. The img control is placed inside a nav bar. Here i ...

What is the significance of the any type in Typescript?

As I delve into learning Typescript, a question arises in my mind. I find myself pondering the purpose of the any type. It seems redundant to specify it when every variable essentially acts as an "any" type by default. Consider this scenario where the out ...

Providing properties to the main Vue.js components

An Issue I'm Facing I am currently attempting to pass a prop to my root constructor. To achieve this, I have been exploring the use of propsData, which I learned about from this resource: var appComponent = Vue.component('app', require(&ap ...

Angular 7 - ALERT: Circular dependency identified:

Suddenly, a lightbulb went off in my head. I encountered two warnings while running ng serve: WARNING in Circular dependency detected: src\app\_services\ignore-interceptor.service.ts -> src\app\_services\index.ts -> sr ...

How can I access and modify a sub collection document in Angular Firestore?

I am facing a challenge in fetching a single document from a Firestore sub collection with the path: database/users/uid/animal/docID Although I have successfully parsed the docID from another component, I am struggling to retrieve the information to displ ...

How can Enums be utilized as a key type for transmitting properties in Vue?

After stumbling upon a helpful method on Stack Overflow that demonstrated how to use an enum to define an object, I decided to implement this in my Vue project. export enum Options { randSize = 'randomSized', timer = 'showTimer', ...

The attribute 'date' is not found within the class 'EmployeeScheduleExceptionModel', however, it is present in the parent class from which it inherits

I am working on a TypeScript project and I have defined my configurations in the tsconfig.json file as shown below: { "include": ["src*"], "compilerOptions": { "target": "es2021", &q ...

What is the best way to verify observables during the ngOnInit phase of the component lifecycle?

Despite reading numerous articles on testing observables, such as learning how to write marble tests, I am still struggling to find a clear solution for testing a simple observable in the ngOnInit lifecycle of my component. ngOnInit(): void { this.sele ...

Error: The property `orderRow` in `_this.Order` is not defined

Currently, I am having some issues while working with classes: The error message displayed is: TypeError: _this.Order.orderRow is undefined The error occurs when attempting to add a new row to the orderRow array. Here is the code snippet: Order Class ...

How do we set and update object properties in Angular 2, specifically with regards to changing the color?

https://i.sstatic.net/N79LB.png I'm having trouble setting note.color=color.color and updating the note. How can we achieve this? Here is the HTML code where the note is not updating when the color changes: <div class="card card-1" *ngFor="let n ...

Pausing or buffering an RxJS 6 observable when the page is inactive

Currently, I am dealing with a stream of letters that need to be arranged in the correct order to form a word. However, an issue arises when the user switches tabs, minimizes the browser, or switches applications - the behavior mimics using setTimeout(), r ...