Tips for passing configuration constants from HTML to a class in Angular 2 for reusing classes

Suppose I am looking to efficiently reuse my Angular 2 components, how can I input configuration directly into the HTML and then pass it to the respective class? However, could this method be vulnerable to potential manipulation in the HTML code by unauthorized users? What would be considered the optimal approach in Angular 2 for creating multiple instances of the same class with varied configurations?

I am facing two main issues:

  • I am only receiving one console output. Does this imply that the class is static in nature?
  • The console output I receive shows as null.

Considering the following code snippets:

<my-comp showWhat="INCOMING"></my-comp>
<my-comp showWhat="OUTGOING"></my-comp>

How can I effectively pass the values 'INCOMING' or 'OUTGOING' to the constructor function?

@Component({
    selector: 'my-comp'
    [..]
})

export class MyComponent {
    constructor(elementRef: ElementRef) {
        console.log("Creating an instance: showWhat value for this instance = "+elementRef.nativeElement.getAttribute('showWhat'));
    }
}

Answer №1

Utilizing @Input instead

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-comp'
  [..]

})

export class MyComponent implements OnInit {
  @Input() displayInfo;
  ngOnInit() {
    console.log(this.displayInfo);
  }
}

Implementing in another component

<my-comp displayInfo="INCOMING"></my-comp>
<my-comp [displayInfo]="someVariable"></my-comp>

Documentation: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#inputs-outputs

Live Demo: https://plnkr.co/edit/xtnGvdlddU7YCIPV36aN?p=preview

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

Learn how to render a single element with multiple child elements within separate `<td>` tags in a table row using React

I'm just starting out with React and I have a code snippet that I'm using to render an HTML table in a component. Is there a more optimized way to achieve this? bodyItems = sorted.map((data) => [ data.employerName, data.sectors.map((sector ...

Can the change listener be used to retrieve the selected option's number in a form-control?

This particular cell renderer is custom-made: drop-down-cell-renderer.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-drop-down-cell-renderer', templateUrl: './drop-down-cell-r ...

Securing API keys in an Angular 2 client-side application: Best practices

Currently, I am working on an Angular 2 project and facing the challenge of making API calls from my service without exposing the keys. While it is recommended to use keys from the backend, I wonder if there is a secure way to handle this directly from th ...

Tips for adjusting fullcalendar's local property in an Angular application

I'm having trouble changing the local property of fullcalendar. I've tried setting it to "en-gb", but it's not working. Can you help me figure out what I'm doing wrong? <full-calendar #calendar defaultView="dayGridMonth" [header]="{ ...

Can we expect Karma to receive updates for upcoming versions of Angular and Jasmine?

We recently attempted to upgrade our company's Angular module, which required updating dependencies as well. Upon upgrading to the latest versions, we encountered an issue with the Jasmine-karma-HTML-Reporter due to its reliance on Jasmine-core 4.x.x ...

Extensible generic type/interface in Typescript

Looking to create a versatile base interface or type that can adapt its properties based on the generic object it receives. It might look something like this: interface BaseObject<Extension extends object = {}>{ a: string; b: string; {...Ext ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

TypeScript overloading error: Anticipated 0 parameters, received 2 instead

I am facing an issue with a class containing an overloaded method that has two versions. One version does not take any arguments, while the second one can take two arguments. class DFD { ... getEndDatetime(): string; getEndDatetime(startTime?: ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

How can I fetch a file using a JavaScript function in Pug/Angular?

Within the Angular7/Pug application, there was previously a file download link implemented in table.component.pug like this: div p File to download: a([href]="downloadLink", download="table.xlsx") some-icon span some-text Now, I a ...

Extending the Request type from Express with Typescript

Having a NodeJs app with Express and Typescript, I am attempting to extend the Request type from Express. I have created an index.d.ts file with the following code snippet: import { User } from "models/user"; declare global { namespace Expres ...

Sorting and categorizing RxJS Observables

Learning about reactive programming is a new and sometimes challenging experience for me. If we have a list of events from a service called event[] The structure of an event is as follows: Event: { beginDate: Date, name: string, type: State } State: ...

Guide to sorting objects in an array using ion-segment within Ionic 2

Below is the code snippet: .html file <ion-segment [(ngModel)]="kmart" color="primary"> <ion-segment-button value="All"> All </ion-segment-button> <ion-segment-button *ngFor="let tabName of buttonName" value={{tabNa ...

An issue has occurred: (SystemJS) XHR error (404 Not Found) while trying to load the resource at http://localhost:3000/ng2-google

I attempted to implement the ng2-google-recaptcha component found at https://github.com/leewinder/ng2-google-recaptcha. I followed the instructions on the page, but encountered the following error: Error: (SystemJS) XHR error (404 Not Found) loading htt ...

Configuring global runtime variables in NextJS for server-side operations

Currently, I am utilizing the instrumentation.ts file in NextJS to retrieve configuration dynamically when the server starts up. My goal is to have this configuration accessible during runtime for all API routes and server-side components. What would be th ...

Attempting to transmit the chosen value, extracted from the selection, into a function, repetitively and multiple times, within an array

I'm attempting to build a dynamic table that allows the user to select the number of rows. Each row contains two dropdown menus with options ranging from 1 to 10. Upon selecting a number from the dropdown, I want it to be passed to a function in the T ...

Using the rxjs repeatWhen operator within the http request pipeline to automatically resend the request if the expected response is not received

I am attempting to simplify my HTTP request pipeline by ensuring that if the response does not contain the required data in res.myCondition, I can use repeatWhen to make another call. However, it seems like I am not using repeatWhen correctly (Angular 8/ R ...

Integrate TypeScript into the current project

As a newcomer to Typescript, I am currently exploring the option of integrating it into my current project. In our MVC project, we have a single file that houses the definitions of all model objects. This file is downloaded to the client when the user fir ...

What is preventing a mapped type from completely resolving a lookup with a generic yet finite key?

Let's break down the issue at hand: type Animal = 'dog' | 'cat'; type AnimalSound<T extends Animal> = T extends 'dog' ? 'woof' : T extends 'cat' ? 'meow' : never; cons ...

Guide on utilizing external namespaces to define types in TypeScript and TSX

In my current project, I am working with scripts from Google and Facebook (as well as other external scripts like Intercom) in TypeScript by loading them through a script tag. However, I have encountered issues with most of them because I do not have acces ...