Is there a way to switch the eventHandler assigned to a particular input element dynamically?

I am facing a dilemma with my child component, which dynamically generates input fields within a parent component.

<app-xxx *ngFor="let el of fieldsElements" 
         [ngModel]="fieldsElements[el.name]"
         ...
         ...
         (keydown)="myFunction(yyy, zzz)">
</app-xxx>

The challenge I am encountering is that I need to trigger myFunction() using the click() event handler when a specific input field is clicked. However, for the remaining fields, I want to maintain the keydown() event. For instance, for one of the dynamically generated input fields, I wish to use click() instead of keydown(). Here's an example:

<app-xxx *ngFor="let el of fieldsElements" 
         [ngModel]="fieldsElements[el.name]"
         ...
         ...
         (click)="myFunction(yyy, zzz)">
</app-xxx>

Is there a way to achieve this in a dynamic manner within the HTML/View? I have experimented with various approaches, such as using *ngIf and implementing if-statements within the typescript file, along with addEventListener(), but none have proven effective.

Any suggestions or insights would be greatly appreciated.

Answer №1

In order to optimize efficiency, it is best to utilize a variable along with the logic 'variable && function'. This ensures that the function is only executed if the variable evaluates to true.

<app-xxx *ngFor="let el of fieldsElements" 
         [ngModel]="fieldsElements[el.name]"
         ...
         ...
         (click)="el.allowClick && myFunction(yyy, zzz)">
         (keydown)="el.allowKeydown && myFunction(yyy, zzz)">
</app-xxx>

Update for example, if your fieldsElements array contains elements like

fieldsElements=[
  {name:"name1",allowClick:true},
  {name:"name2",allowKeyDown:true},
  {name:"name3"}]

"name1" will execute the function on (click), "name2" on (keyDown), and "name3" will not execute anything.

Answer №2

If you're looking to jazz up your <app-xxx> tag, consider experimenting with various templates and switching between them using NgIf-Else

Answer №3

If you want to toggle elements based on a condition, you can use *ngIf in Angular. Here is an example:

<div *ngFor="let item of items">
    <div *ngIf="name === 'somename'" (click)="myFunction()">
    // Display element if condition is met
    </div>
    <div *ngIf="name !== 'somename'" (keydown)="myFunction()">
    // Display element if condition is not met
    </div>
</div>

By using *ngIf with the condition, you can control which elements are displayed based on the value of 'name'. It's a simple way to dynamically switch between elements without changing handlers directly.

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

``In Angular 12, what are the best ways to tackle the CORS problem?

I am currently working on a project using Angular and I have encountered an issue with CORS error while trying to submit the login API. I have also included a screenshot of the error for reference. Any advice or suggestions would be greatly appreciated. AP ...

JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads - const storage = multer.diskStorage({ destination: (req, file, callback) => { let type = req.params.type; let path = `./data/${type}`; fs.mkdirsSync(path); callback(null, path) ...

Move the assets folder in Angular to Azure Storage

Looking to streamline my Angular application by transferring all the assets to Azure Storage. Rationale: The assets folder in my repository is cluttered with large, static files that never change. Since we are hosted on Azure, the plan is to move the ass ...

Discovering the true nature of a generic Type in TypeScript

Consider this scenario involving TypeScript interface IApiCall<TResponse> { method: string; url: string; } Above interface is utilized in the following method; const call = <TResponse>(api: IApiCall<TResponse>): void => { ...

Create a recursive CSS style for an angular template and its container

I am struggling with styling CSS inside an ng-container that is used in a tree recursive call to display a tree hierarchy. <ul> <ng-template #recursiveList let-list> <li *ngFor="let item of list" [selected]="isSelected"> <sp ...

Error encountered in Angular Html2Pdf: Unable to assign the 'adoptedStyleSheets' attribute on 'ShadowRoot' due to DOMException

Looking for assistance in implementing html2pdf with Angular 12 to convert specific parts of an HTML page into a downloadable PDF. ERROR MESSAGE An error occurred while trying to execute the code: index-7a8b7a1c.js:150 Uncaught (in promise) DOMExce ...

Refreshing display with information received from web socket in Angular 5

On my page, I am receiving an array of data upon page load and displaying it using the *ngFor directive. Additionally, there is a connection established to a Web Socket to receive updated data, which in this case pertains to a timetable for boat trips. The ...

Using Angular Material to dynamically hide columns in a table that is being created on the fly

Is there a way to hide columns in my table based on the ID value sent to the page upon opening it? While researching, I found a method for tables with dynamically generated columns in this post: https://github.com/angular/components/issues/9940. However, t ...

Encountering an Error with PrimeNG dataTable when Using a p-checkbox within a p-column

My Datatable is currently functioning properly: <p-dataTable [value]="myObjects" [rows]="10" [paginator]="true" [pageLinks]="3"> <p-column field="name" header="Name"></p-column> <p-column field="size" header="Size"></p-c ...

Increment the integer value every time the button is pressed in a continuous manner

As a beginner in the world of Android development, I have encountered a little challenge that I hope someone can help me with. I have implemented two buttons - one to decrease and one to increase a value displayed in a TextView between them. The current f ...

Localization of labels and buttons in Angular Owl Date Time Picker is not supported

When using the Owl Date Time Picker, I noticed that the From and To labels, as well as the Set and Cancel buttons are not being localized. Here is the code snippet I am using to specify the locale: constructor( private dateTimeAdapter: DateTimeAdapter&l ...

When employing class decorators, it is essential to use the Angular2 reflect-metadata shim

Exploring server rendering with Angular2 using the universal starter example inspired me to experiment with gulp instead of webpack. However, I encountered an issue when the server started: /Users/jaumard/IdeaProjects/trails-angular2-isomorphic/node_modul ...

What is preventing type guarding in this particular instance for TypeScript?

Here is an example of some code I'm working on: type DataType = { name: string, age: number, } | { xy: [number, number] } function processInput(input: DataType) { if (input.name && input.age) { // Do something } e ...

What is the best way to resize a div located below a dynamic div in order to occupy the available space?

My website has a dynamic div1 and a scrollable table inside div2. I need the div2 to take up the remaining height of the window, while ensuring all divs remain responsive. I've tried using JavaScript to calculate and adjust the heights on window loa ...

Is it possible to link fields with varying titles in NestJS?

Currently, I am developing a NestJS application that interacts with SAP (among other external applications). Unfortunately, SAP has very specific field name requirements. In some instances, I need to send over 70 fields with names that adhere to SAP's ...

Is there a way in Angular 1.5 to compile the HTML of a parent component from within a child component?

I have created two angular components called app-menuitem and app-menu. The app-menu component contains a list of app-menuitems as its children, without using transclude. App-menuitem Component: angular.module('app') .component('appMen ...

The parameter "path" must be a string type. Instead, we received type undefined. This issue is specific to Ionic 4 on Windows

Encountered an unexpected error that is hindering development on a Windows PC, even though building the app works fine on a Mac. The error message received is: cordova build android --stacktrace config file undefined requested for changes not found at ...

Angular: Is it possible to gather data from multiple observables and store it in a regular array?

I am facing a challenge where I need to retrieve data from the backend and pass it on to a child component. Here is what I have so far: ... @Component({ selector: 'my-component', template: `<my-child-component [data]="data">& ...

Arrange the elements within the anchor tag in a vertical line using Angular Material

Is there a way to style the elements within an anchor tag in Angular Material so that they display in a single line? I am looking for the CSS solution to achieve this outcome. This is my current HTML code: <a mat-list-item [routerLink]="['das ...

Ensure that the key and value types in a Typescript Map are strictly specified

Is it feasible to generate a map that consists of key-value pairs, where the key is represented by a string and the value corresponds to an object containing specific properties defined by mapValue? type mapValue { first: string; second: boolean; } Yo ...