Create a new function and assign it to "this" using the button inside ngFor loop

I am working with a li tag that has a *ngFor directive:

<li *ngFor="let items of buttons">
  <button (click)="newMap(items.id, $event)">
    {{ items.name }}
  </button>
</li>

The buttons array looks like this:

buttons = [
  {name: 'Berlin', id: 'mapBerlin'},
  {name: 'New York', id: 'mapNewYork'},
  {name: 'Tokyo', id: 'mapTokyo'}
]

I am assigning a (click) method to the button tag:

(click)="newMap(items.id, $event)"

In TypeScript:

newMap($event) {
  console.log($event)
}

When I click on button number 1, I see this message in the console:

  • mapBerlin

For button number 2:

  • mapNewYork

and so on.

Is there a way to create a function like this one?:

newMap(this.id) {
  this.markers = this.id
}

I would like to change this.markers to this.id (e.g., this.mapBerlin, this.mapNewYork, etc.)

Answer №1

This is acceptable

<li *ngFor="let items of buttons">
  <button (click)="newMap(items.id, $event)">
    {{ items.name }}
  </button>
</li>

Your customized function

newMap(id, event){
this.markers = id}

Answer №2

It seems to me that your code should function in this manner:

createNewMap(newId) {
  this.markers = newId;
}

All you need to do is set the provided id.

Answer №3

Give this a shot:

<div *ngFor="let option of choices">
    <button (click)="selectOption(option)">
        {{ option.text }}
    </button>
</div>

selectOption = (option) => {
    this.selectedOption = option.id;
}

Answer №4

There's no need to alter the function's context:

Simply use the following code:

newMap(id, event){
    this.markers = id;
}

If you still want to change the context of this, you can achieve it like this:

<li *ngFor="let items of buttons">
  <button (click)="newMap.call(items, $event)">
    {{ items.name }}
  </button>
</li>

And in TypeScript:

const componentContext = this;
.
.
.
newMap(event){
    componentContext.markers = this.id;
}

However, I wouldn't recommend this approach. It's a bit hacky.

Answer №5

The following code snippet seems to be working fine:

newMap = (item) => {
    this.markers = item.id;
}

However, upon checking the console, I noticed this error message:

'mapTokyo'. Only arrays and iterables are allowed

Answer №6

What's the reason?

options = [
  {name: 'Paris', id: this.mapParis},
  {name: 'London', id: this.mapLondon},
  {name: 'Rome', id: this.mapRome}
]

resulting in the entire object being obtained in the id

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

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

Verify the legitimacy of the object

I'm encountering an issue while attempting to create a function that verifies the validity of an object. const isPeriodValid = (period: Period | null): boolean => { return period && period.start && period.end; } export interfac ...

Encountering the error below while attempting to run ng serve

Having an issue with VSCode as a new user. When running ng serve, I encountered the following error message: PS C:\Windows\System32\x-app> ng serve --configuration=it An unhandled exception occurred: Workspace config file cannot le loa ...

Using Promise.all for multiple function calls

I have several functions set up like this: private async p1(): Promise<Result> { let p1; // Do some operations. return p1; } private async p5(): Promise<void> { // Make a call to an external API. } Some of these functions c ...

"Troubleshoot: Main child route in Angular 2 not functioning correctly

Below is the configuration of the child routes for my project: export const ProjectRouter: RouterConfig = [ { path: 'projects', component: MainProjectComponent, children: [ { path: 'new', component: NewProjectComponent, can ...

Generating a component selector using an @Input parameter

Is it feasible to dynamically create a selector in Angular programmatically? Consider a scenario where there is a parent component named header.component with the following structure; export class ContentHeaderComponent { @Input() iconName: string; } ...

Decompressing an array within a function invocation

Is there a method to pass an array's elements as arguments to a function? For instance, in Python I can accomplish this using: user = ["John", "Doe"] def full_name(first_name, last_name): return first_name + last_name Therefore, full_name(*user ...

The 'RouterLink' JSX element type is missing any construct or call signatures

While researching this issue on the internet and Stack Overflow, I've noticed a common theme with problems related to React. An example can be found here. However, I am working with Vue and encountering errors in Vue's own components within a new ...

Encountering Gyp Errors During NPM Install in an Angular 5 Project

I encountered some gyp errors when trying to run "npm install" in my Angular 5 project. I'm not sure why these errors are occurring; perhaps someone here has seen similar issues before. https://i.stack.imgur.com/mMRO4.png I attempted various trouble ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

A technique for deactivating reactive forms control within a nested formArray

Is there a way to selectively disable individual controls within the 'fields' group which is nested under this.form.get('groups').controls? I know how to disable an entire group by using this.form.get('groups').controls.disabl ...

"Utilize Typescript for defining the parameter type in this

defineProperties(Element.prototype, { querySelector: { value: querySelectorPatched, writable: true, enumerable: true, configurable: true, }, querySelectorAll: { value(this: HTMLBodyElement): NodeListOf< ...

Modify the size of HTML elements when a button is clicked using Angular

Check out this code snippet I wrote: <div> <p>First</p> <p>Second</p> <div> <p>Third</p> <p>Fourth</p> </div> <button>+</button> <button>+</button> I'm trying t ...

Angular Placeholder Positioned at the Top

Hello, I am a beginner in Angular and need to create an input field that looks like this: https://i.sstatic.net/LUXfJ.png Everything is going fine except for the Vorname placeholder at the top. How can I place it there? Currently, I am utilizing Angular ...

Using getter functions and Visual Studio for TypeScript

In my TypeScript classes in Visual Studio, I have been implementing getter functions. I find that using getter functions helps to clean up my code, although there is one issue that I would like to address. class Foo { doWork(){ console.log(this.bar ...

The bar graph dataset is not correctly configured when utilizing ng2 charts and ng5-slider within an Angular framework

Currently, I am working with a range slider and bar graph. My goal is to dynamically change the color of the bar graph using the range slider. While I have managed to successfully alter the color of the bars, I am facing an issue where the data displayed ...

Enhance your TypeScript module with parcel augmentation

I'm having issues shipping a library that utilizes typescript module augmentation with Parceljs. It appears that the module augmentations are not getting bundled properly, preventing me from utilizing the properties in the project that imports the lib ...

Tips to enable cross-domain file downloads from Google Storage in Angular 5

We have integrated Videogular2 player (VG player) into our website to enhance the video viewing experience. Currently, we are looking to incorporate subtitles into one of our videos by using a subtitle file (.vtt) stored in Cloud Storage. However, when at ...

Why does TypeScript not recognize deconstructed arrays as potentially undefined variables?

When looking at the code snippet below, I was under the impression that the destructured array variables, firstName and lastName, would be classified as string | undefined. This is because the array being destructured could have fewer variables compared ...