Accessing the value of a FormControl in HTML代码

Modifying the value of a form select element programmatically presents an issue.

Even after changing the value in the form, the paragraph element "p" remains hidden.

However, if you manually adjust the form's value, the visibility of the "p" element functions correctly.

Expected Outcome:

The <p> tag should be visible when the `field1` FormControl value equals `1`.

Please advise on what might be causing this problem?

component.html

<form [formGroup]="formGroup">
  <mat-form-field class="mb-4" fxFlex="100">
      <mat-select #field1 formControlName="field1" placeholder="Data type" required>
        <mat-option value="0" selected>Boolean</mat-option>
        <mat-option value="1">Int</mat-option>
        <mat-option value="2">Double</mat-option>
        <mat-option value="3">String</mat-option>
        <mat-option value="4">Byte array</mat-option>
        <mat-option value="5">Object</mat-option>
      </mat-select>
    </mat-form-field>
</form>

<p *ngIf="field1.value === '1'">Integer</p>

<button mat-raised-button color="primary" (click)="onClick()">Set 'Int'</button>

component.ts

export interface Item {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
  public data: Item[] = [
    {value: '1', viewValue: 'Option 1'},
    {value: '2', viewValue: 'Option 2'},
    {value: '3', viewValue: 'Option 3'}
  ];
  public formGroup: FormGroup;

  constructor(private _formBuilder: FormBuilder){

  }

  ngOnInit() {
    this.formGroup = this._formBuilder.group({
      field1: [1, null]
    });
  }

  onClick(){
    this.formGroup.controls.field1.setValue('1');
  }
}

Example Stackblitz

Answer №1

Don't forget about an alternative to the #template reference variable, try:

formGroup.get('field1').value

therefore, modify the HTML Code accordingly:

<p *ngIf="formGroup.get('field1').value === '1'">Integer</p>

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

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...

Angular's change detection is currently inactive

I need to toggle the visibility of a button based on the value of a boolean variable using the Output property. However, I am facing an issue where the button remains hidden even after the variable is updated with a true value. Parent Component.ts showE ...

Making a REST API call with an ID parameter using Angular

I am currently working on an Angular application that interacts with a REST API. The data fetched from the API is determined based on the customer ID, for example: api/incident?customer_id=7. I am unsure of how to incorporate this into the API URL and serv ...

An issue has occurred: [ERR_REQUIRE_ESM] You must utilize the import statement in order to load an

These are the snippets of code I'm working with: index.ts import { MikroORM } from "@mikro-orm/core" import { __prod__ } from "./constants"; import { Post } from "./entities/Post"; import microConfig from "./mikro-o ...

TS2349 emerges when incorporating lazy-loading in React

I've been working on refactoring a React 18 app to incorporate lazy loading, following the guidelines provided in the official documentation: One effective method to implement code-splitting in your application is through the dynamic import() syntax ...

The `react-router-dom` in React consistently displays the `NotFound` page, but strangely, the active class for the home page does not get

Currently, I am utilizing "react-router-dom": "^6.4.1" in my application and encountering two main issues: Upon navigating to another page, the home page retains the active class, resulting in both the new page and the home page disp ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

Regex for US zip code with an optional format

Searching for a regular expression to validate US zip codes. I have come across multiple examples, but none of them cater to the scenario where the zip code is optional. The input field I am working on does not require a zip code, so it should accept a 5 ...

Guide on linking enum values with types in TypeScript

My enum type is structured as follows: export enum API_TYPE { INDEX = "index_api", CREATE = "create_api", SHOW = "show_api", UPDATE = "update_api", DELETE = "destroy_api" }; Presently, I have a f ...

What steps can I take to concentrate on a particular mat-tab?

<mat-tab-group mat-stretch-tabs #tabGroup (focusChange)="tabChanged($event)" [selectedIndex]="0"> <mat-tab label="DATOS EXPEDIENTE"> <div class="example-large-box mat-elevation-z4"> <app-informe-expediente></app ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

Improper application of Angular bindings in Chrome when navigating to a page using the browser's back button

Have you encountered this issue before? I have a few textboxes generated within an ngFor loop: <tr *ngFor="let tableRow of lineItems; trackBy:trackByIndex; let rowIndex = index; "> <td class="psavingsSmallerGridCell"><input c ...

The Battle of Extends and Intersection in Typescript

Typescript's concept of extension is akin to C++'s inheritance. Intersection in Typescript involves creating a new object with all the properties from the intersected classes. Why utilize intersection when extends keyword can already merge ...

Enhancing State Management with CombineReducers in TypeScript

export const rootReducer = combineReducers({ login: loginReducer, }); Everything is working fine with the current setup, but I encountered an issue when attempting to combine another reducer: export const rootReducer = combineReducers({ login: lo ...

What is the correct way to declare a DocumentReference type within an Angular TypeScript interface?

Thank you for taking the time to read my inquiry. Technologies used: Angular 13, Firebase Firestore v9 database, and Firebase Authentication. My question pertains to the process of signing up a user through Firestore Authentication. Upon signup, I need ...

When trying to compile FirebaseUI with typescript and react-redux, users may encounter issues

I'm attempting to implement firebaseui for a login feature in react-redux using typescript. Here is the code snippet: import firebase from 'firebase'; import firebaseui from 'firebaseui'; import fire from '../FirebaseCreds&ap ...

Setting values to variables within a component to enable universal access throughout the component in Angular 2

In my Angular 2 project, I have a function that retrieves data from a database using an API. I've created a function that stores the data successfully in a variable named "ReqData", which is of type "any". this._visitService.getchartData().subscrib ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

Steps for upgrading from Ionic framework v1.2.4 to Ionic framework v2.0.0-beta with npm

Currently, I am in the process of upgrading my Ionic framework from version 1.2.4 to the latest version 2.0.0-beta using the node package manager (npm). I stumbled upon a guide on the official documentation site that instructed me to execute this command ...

Issue: The CSS loader did not provide a valid string output in Angular version 12.1.1

I am encountering 2 error messages when trying to compile my new project: Error: Module not found: Error: Can't resolve 'C:/Users/Avishek/Documents/practice/frontend/src/app/pages/admin/authentication/authentication.component.css' in &apos ...