Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application,

I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should:

  • Appear only when the textarea is focused
  • Disappear when the textarea is out of focus (clicked outside)
  • Clear the text within the textarea upon clicking

Here's how I have set it up:

<form [formGroup]="form">
    <p>This form is reactive<br />
        <textarea (focusin)="componentMethod($event)" (focusout)="onfocusout($event)" formControlName="test" #test ></textarea>
        <button  *ngIf="showNotes" type="reset" id="close-resetNotes" class="close" aria-label="Close" (click)="resetNotes()">
    <span aria-hidden="true">×</span>
  </button>
    </p>
</form>

In the TypeScript part:

export class AppComponent {
  public form: FormGroup;
  showNotes = false;
  @ViewChild("test") textareaElement: ElementRef;

  constructor(private formBuilder: FormBuilder) {}

  public ngOnInit() {
    this.form = this.formBuilder.group({
      test: ["some text", Validators.nullValidator]
    });
  }

  public componentMethod(event) {
    this.showNotes = true;
  }

  public onfocusout(event) {
    this.showNotes = false;
  }

  resetNotes() {
    this.form.patchValue({ test: "" });
    this.showNotes = true;
  }
}

The issue encountered is that the textarea loses focus immediately upon clicking the clear button, before applying the clear action. Any suggestions on how to resolve this?

Answer №1

To fulfill your needs, utilizing the focus and blur events of a textarea along with a variable is key. I have generated a code snippet that aligns with your specifications. Feel free to review it here

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

Tips for showing a value in a disabled text input box

When users access the page, the table should appear as follows: Marks Per Answer Total Marks Marks Remaining (blank text input) 4 4 (blank text inp ...

Ways to create a table with columns from various fields obtained through an API call

Looking to preprocess data received from an API, the raw data is structured as follows: Desiring to dynamically generate a table with columns based on the fields task_name and saved_answers. It's important to note that saved_answers might contain var ...

The data type 'void | Observable<any>' cannot be assigned to the type 'ObservableInput<any>'. Specifically, the type 'void' cannot be assigned to 'ObservableInput<any>'

I encountered an error in my visual studio code: Argument of type '(query: string) => void | Observable' is not assignable to parameter of type '(value: string, index: number) => ObservableInput'. Type 'void | Observable& ...

An HTML editor that provides syntax highlighting for HTML code within PHP echo statements

Whenever we employ the echo function in PHP, the content within the quotes is considered as HTML. In certain HTML editors that I have tried, they simply highlight all of the HTML code in one single color, which can be a bit perplexing. Does anyone know o ...

Reliable selection menu for changing fields

Can someone help me with this coding issue? I am attempting to create a dependent dropdown menu where selecting a category will also display relevant equipment. However, in my current setup, only the category field is functioning properly. When I try to a ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

What are the most effective techniques for utilizing JavaScript modules in both the Server and Browser environments?

Currently, I am in the process of developing a JavaScript project that utilizes NodeJS. There are certain objects that need to be shared between the client and server side. I attempted to employ the module system in Node, but struggled to find an appropria ...

Unexpected Issues with Page Refresh in AngularJS

I am currently working on an Angular application using the MEAN stack. Here's a scenario: imagine you have an express route that queries the database and sends the results back in the response: app.get('/api', function(req, res){ Todo.f ...

Can you explain how to incorporate global functions from a javascript library into an Angular 2 project?

Recently I started working with angular-cli and came across a situation where I have an index.html containing a javascript script with some global functions. I want to access these functions in multiple parts of my application. As someone who is new to A ...

Arranging elements on a website using CSS styling

I'm interested in creating a button <Button id="Button" text="Hey" />. I would like to know how I can position it on a webpage exactly where I want it, rather than it just appearing randomly without content. ...

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

Verify if there is a date present within the JSON entity

I have a PHP array containing date strings and I want to validate them using a native HTML5 date input element. To achieve this, I have converted the date array into a JSON object for use with JavaScript: <script> var date_array = <?php echo json ...

What is the best way to center this image horizontally within its variable-sized parent container?

I am currently working on a webpage that has a responsive design. The page features a list of products, with the product listing adjusting in size as the page width changes. My goal is to center the product image within its container, ensuring that the i ...

Unexpectedly, a significant ngrx createEffect leads to an unusual error following an update, but the issue vanishes when certain code snippets like tap or filter are disabled

I have been in the process of upgrading a massive Angular 12 project to Angular 13 and have completed several steps. One significant change was the rewriting of Effects using a newer approach like createEffect(() => instead of @Effect However, during ...

Switch up the item's background in the dropdown list within Kendo UI Angular

Looking for a solution to highlight text and change background color in a dropdown list based on certain conditions. I searched the official Kendo forum without success. Any guidance or suggestions on how to resolve this issue would be greatly appreciate ...

Creating dynamic layouts using Handlebars.js recursion

I'm working with a basic object hierarchy that includes: Category String name List childCategories; My goal is to use handlebars to represent this structure in a generic manner, but I'm struggling on how to nest layouts. Here's the curre ...

Running Applications with React Using Command Line Interface (CMD)

I'm currently working on creating a .cmd file to handle the installation of dependencies and then execute my React application. Following some research, I have come up with the following code snippet inside my .cmd file: @echo off npm install pause np ...

`Animate your divs with slide in and slide out effects using

Currently, I am in the process of replicating a website and facing some challenges. This site is my inspiration for the project. I have managed to create a sliding effect using CSS, making the div slide in and out from the same direction. However, I want ...

"How to set the header in AngularJS when opening a new window with a GET request URL

Can anyone provide guidance on setting headers and opening a URL (https://www.example.com) in a new window without including sensitive authentication information in the URL parameters? I am working with AngularJS for this task. I have searched through exi ...

Attempting to transfer a newly created element from one location to another within the document after it has finished

I'm currently updating the design of my website. The currency selector app by Shopify is placed at the bottom, which has caused confusion for my international customers. To resolve this issue, I want to move it to a specific div class called .CSPositi ...