Utilizing an array element as a parameter for a function in an Angular template

My Angular2 application includes the following code in app.component.ts:

...
export class AppComponent {
    // themes array
    readonly themes = ['assets/default-theme.css', 'assets/test-theme.css', ...];

    // theme setter
    setTheme(href: string) {
        setThemeLinkHref(href);
        console.log('The theme has been updated to: ' + href);
    }
    ...
}

In the app.component.html template, I have the following code:

...
<button (click)="setTheme(themes[0])">Default</button>
...

When using this approach, I notice that 'undefined' is logged as the theme's href:

The theme has been updated to: undefined

Is there a way to correctly pass a specific item from an array as an argument to a function?

Answer №1

To avoid repeating code, you can implement the use of ngFor in the following way:

<button mat-menu-item  *ngFor="let theme of themes" (click)="setTheme(theme)"> {{theme.name}}</button>

Additionally, adjust your themes array as shown below without using the readonly keyword to define access permissions:

themes = [{'theme':'assets/default-theme.css','name':'Default'}, {'theme':'assets/test-theme.css','name':'Test'}];

Answer №2

If you remove the readonly modifier, everything appears to function correctly.

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

Error: 'process' is not defined in this TypeScript environment

Encountering a typescript error while setting up a new project with express+ typescript - unable to find the name 'process'https://i.stack.imgur.com/gyIq0.png package.json "dependencies": { "express": "^4.16.4", "nodemon": "^1.18.7", ...

The value of Angular Input remains unchanged within a FormArray

I am experiencing an issue with the Sequence No in my PreprocessingForm's FormArray. When I add a new row, the Sequence No does not change as expected. <tr class="mat-row" *ngFor="let dynamic of PreprocessingForm.controls.arithmeticI ...

Organizing items by a string attribute in TypeScript

My data consists of an array of objects with a structure similar to this: export class AccountInfo { accountUid: string; userType: string; firstName: string; middleName: string; lastName: string; } NOTE: I opted not to use an enum for userType ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Discover the method for converting a local file into a string

Looking to retrieve and read an SVG file in Angular 6 from the assets folder as a string. I've attempted the following: this._htmlClient.get('../../assets/images/chart1.svg').subscribe(data => { console.log('svg-file: ', ...

The anticipated outcomes are not achieved when utilizing environmental variables in Angular 2

Is it expected that when we use ng serve --env=prod, it should work with the values set in environment.prod.ts? Well, in my experience, it doesn't seem to be working as expected as I always receive the values from environment.ts (which is the developm ...

How can I dynamically replace a specific element inside a .map() function with a custom component when the state updates, without replacing all elements at once?

I'm currently developing a task management application and I need to enhance the user experience by implementing a feature that allows users to update specific tasks. When a user clicks on the update button for a particular task, it should replace tha ...

The Cypress-TinyMCE package consistently returns undefined for the editor instance when using TypeScript

My current project involves building a React JS application with TypeScript, where I utilize the TinyMCE editor within a form. To further enhance my development process, I am incorporating integration tests using Cypress in TypeScript. However, I have enco ...

There seems to be a compatibility issue between Angular 16 and Bootstrap 5 styling

In my angular.json, I have defined my styles in the following way: "styles": [ { "input": "node_modules/bootstrap/dist/css/bootstrap.min.css", "bundleName": "ltrCSS" }, { "input": "node_mod ...

Error: Attempting to assign a value to a property that is not defined - Uncaught TypeError: Unable to set the property 'other_user_image

I've been struggling to set the image src attribute using a typescript function, but I keep encountering a "cannot set property of undefined error." It's frustrating because I can't seem to figure out where I'm going wrong. Here is the ...

Using Typescript to combine strings with the newline character

Currently, I am delving into Angular2 and facing the challenge of creating a new line for my dynamically generated string. For example: input: Hello how are you ? output: Hello how are you? Below is the code snippet: .html <div class="row"> ...

Ecommerce Template for Next.js

I am new to the world of web development and I have a project involving customizing a Next.js ecommerce template. Since I'm still learning programming, I would appreciate a simple summary of the steps I need to take in order to achieve this. The speci ...

Every time I try to run my Angular app, it crashes. I've already tried reinstalling Node and rebooting

After attempting to relocate an angular project into a different folder yesterday, I encountered issues when trying to start the app using ng serve. Interestingly, creating a new project and running ng serve resulted in the same error. Both projects were ...

Results are only displayed upon submitting for the second time

Struggling with implementing a change password feature in Angular 7, On the backend side, if the current password is incorrect, it will return true. An error message should appear on the Angular side, but I'm encountering an issue where I have to cl ...

Charts are not displaying properly in Angular 10 when using ng2-charts

My application is supposed to display charts, but for some reason, the charts are not loading. When I check the DOM, I see the element being created with ==$0, which is confusing to me. I am using Angular Material, but I don't think that should be a ...

Guide on how to focus on a specific node programmatically within a PrimeNG Tree component

One of the features of PrimeNG is the ability to scroll to a specific TreeNode: To implement this in html: <p-tree #mytreeid id="mytree"></p-tree> In an Angular application: @ViewChild("mytree") mytree: Tree; // selection represents the Tre ...

Encountering an issue in tsconfig while trying to change the module to ES201

After researching LitElement documentation, I updated my tsconfig.json file to reflect the following configuration: { "compilerOptions": { "target": "ES2017", "module": "ES2017", "moduleResolution": "node", "experi ...

Can I integrate @types/pkg into my custom library to automatically have types included?

Imagine I am creating a library that utilizes types from the Definitely Typed repository (such as @types/pkg). Would it be feasible for my package to automatically include these types when installed, eliminating the need for consumers to separately instal ...

Show child component and its content in parent component based on certain conditions

To show a child component (along with its ContentChildren) within the template of a parent component based on certain conditions. app.component.html <parent> <child #initial> <span>Player</span> </child> <child ...

combine elements from an array into a formatted string and sort them

I'm trying to sort a string based on the length of its items This is the array const quotes = [ {ref1: 'CE255X', price_u: '1024100'}, {ref1: 'M-TK137', price_u: '65400'}, {ref1: '126A‎‎‎', ...