Compulsory selection and input fields in Angular forms

I need the select and input fields of the form to be required. I attempted to follow the angular website tutorial, but it didn't work for me or I might have made a mistake. How can I resolve this issue?

Below is my HTML file:

<form [formGroup]="angForm" class="form-inline my-5 my-lg-0">
  <select #emoji class="textboxclass" type="text" placeholder="Emoji" aria-label="Post" required>
    <option value="" disabled selected>Emoji</option>
    <option value="angry" style="background-image:url(~assets/emoticons/png/angry.png);">angry</option>
    <option value="bored" style="background-image:url(~assets/emoticons/png/bored.png);">bored</option>
    <option value="confused" style="background-image:url(~assets/emoticons/png/confused.png);">confused</option>
    <option value="embarrassed" style="background-image:url(~assets/emoticons/png/embarrassed.png);">embarrassed</option>
    <option value="happy" style="background-image:url(~assets/emoticons/png/happy.png);">happy</option>
    <option value="kissing" style="background-image:url(~assets/emoticons/png/kissing.png);">kissing</option>
    <option value="unhappy" style="background-image:url(~assets/emoticons/png/unhappy.png);">unhappy</option>
  </select>
  <input #text id="postText" name="postText" class="form-control" type="text" placeholder="Write your Mood" aria-label="Post"
         formControlName="postText" required>
  <div *ngIf="angForm.controls['postText'].invalid && (angForm.controls['postText'].dirty
  || angForm.controls['postText'].touched)" class="alert alert-danger">
    <div *ngIf="angForm.controls['postText'].errors.required">Text required</div>
  </div>


</form>

<button class="btn btn-outline-success my-2 my-sm-0" (click)="postMood(emoji.value, text.value)">Post </button >

And here is my component file:

import { Component, OnInit } from '@angular/core';
import {PostServiceService} from './post-service.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-post-service',
  templateUrl: './post-service.component.html',
  providers: [PostServiceService],
  styleUrls: ['./post-service.component.css']
})
export class PostServiceComponent implements OnInit {
  angForm: FormGroup;

  constructor(private postService: PostServiceService, private  fb: FormBuilder) {this.createForm(); }

  ngOnInit(): void {
  }

  createForm() {
    this.angForm = this.fb.group({postText: ['', Validators.required]});
  }

  postMood(emoji, text): void {
    this.postService.postMoods(emoji, text);
  }

}

Answer №1

Include emoji selection within the form group.

this.angForm = this.fb.group({
  emoji: ['', Validators.required],
  postText: ['', Validators.required]
});

Assign the formControlName to the select element

<select formControlName="emoji" ...>

Ensure the button is disabled to prevent mood posting without all required fields.

<button [disabled]="angForm.invalid" ...>

You can also access form values without referencing elements like this

postMood() {
  const emoji = this.angForm.get('emoji').value;
  const text = this.angForm.get('postText').value;
  this.postService.postMoods(emoji, text);
  // Reset form values
  this.angForm.reset();
}

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

Displaying index.html exclusively using Angular Capacitor

I am currently working on converting my Angular application into an Android application using Capacitor. I have successfully installed Capacitor in my Angular project, which includes routing functionality. Here are the versions of the tools I am using: &qu ...

Using dictionary keys as valid property values

I have put together a dictionary like so: const iconTypesDictionary: { [key: string]: IconPrefix } = { solid: 'fas', regular: 'far', light: 'fal', } My goal is to be able to utilize the keys of this dictionary as potent ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

Angular 8 carousel featuring a dynamic bootstrap 4 design with multiple images and cards displayed on a single slide

I am currently working on a dynamic carousel that should display multiple cards or images in one row. Initially, I faced an issue with the next and previous buttons not functioning properly when trying to display multiple cards in one row. After some onlin ...

Encounter an error during testing with jest where the issue arises from converting circular structure to JSON in moment.js on a specific line

While working with Angular and Jest, I encountered an error when incorporating moment.js into my code. Below is the import statement in my component: import * as moment from "moment"; The line where the error occurs: const date = moment(new Dat ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Error TS2322 occurs during compilation in Typescript when using ng.IPromise

Having some issues while using Angular 1.x with Typescript. Here is the code causing trouble: get(id): ng.IPromise<Server.MyItem> { return this.$http.get(`${this.baseAddress}/${id}`).then(d => d.data); } After compiling with tsc, I am encoun ...

The npm installation process seems to be taking an eternity in this Angular 2 project

Recently, I've been facing a frustrating issue with my Angular 2 project. Whenever I run the npm install command, it seems to be stuck in an endless loop. The progress bar fills up, only for a new npm install command to appear, followed by another pro ...

Using TypeScript without specifying a specific argument in the any type

My function accesses local/session storage, but there is a condition that it can only be called if the window is defined. This function takes a generic args argument which I simplified to have a type of any[]. While using the useSessionStorage function, ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. https://i.sstatic.net/T9UKR.png Below is my API code: https://i.sstatic.net/kkwqs.png Here is the service code: https://i.sstatic.net/IUMSd.png This section ...

Comparing two arrays in Angular through filtering

I have two arrays and I am trying to display only the data that matches with the first array. For example: The first array looks like this: ["1", "2" , "3"] The second array is as follows: [{"name": "xyz", "id": "1"},{"name":"abc", "id": "3"}, ,{"name ...

Attach an event listener to a particular textarea element

Currently, I am developing a project in Next.js13 and my focus is on creating a custom textarea component. The goal is to have this component add an event listener to itself for auto-adjusting its height as the user types. Below is the relevant section of ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

Strategies for managing a situation where a class is called during runtime

Can anyone assist me with an Angular issue? I am trying to dynamically add the abc class when the show class is present, and remove the abc class when the show class is hidden. I am working with Angular 6 and my current conditions are as follows. Any help ...

The Angular build process was successful on a local machine, however, the Angular build failed when

I am facing a challenge with my Angular project that I want to deploy on Gitlab Pages. Initially, when I execute: ng build --prod locally, the build is successful. Below is my .gitlab-ci.yaml: image: node:8.12.0 pages: cache: paths: - node_mo ...

Tips for changing the name of a directory in an Angular 6 application

Looking for guidance on renaming a folder in an Angular 6 project's components directory. Is there a safe way to do this without causing any issues, or is it as simple as just changing the name of the folder? Using Visual Studio Code as my IDE. ...

Exploring Scroll Functionality for Inner Components Within Mat-tab

I am currently working on a small attendance project that involves using table components within mat-tab elements. However, I am facing an issue where the overflow from the table causes the entire component to scroll, when in fact I only want the table its ...

Leverage Prisma's auto-generated types as the input type for functions

Exploring the capabilities of Prisma ORM has led me to experiment with creating models and generating the PrismaClient. Initially, I thought it would be possible to utilize the generated types for variables and response types, but that doesn't seem to ...

What is the best way to send an enum from a parent component to a child component in

I'm trying to send an enum from a parent component to a child component. This is the enum in question: export enum Status { A = 'A', B = 'B', C = 'C' } Here's the child component code snippet: @Component({ ...

Encountering the "Unrecognized teardown 1" error when subscribing to an Observable in Typescript and Angular2

Having trouble with using an Observable in my Angular2.rc.4 Typescript app. Check out the plunker for it here: https://embed.plnkr.co/UjcdCmN6hSkdKt27ezyI/ The issue revolves around a service that contains this code: private messageSender : Observable< ...