How to use attributes in Angular 2 when initializing a class constructor

Is there a way to transfer attributes from a parent component to the constructor of their child components in Angular 2?

The process is halfway solved, with attributes being successfully passed to the view.

/client/app.ts

import {Component, View, bootstrap} from 'angular2/angular2';
import {Example} from 'client/example';

@Component({
  selector: 'app'
})
@View({
  template: `<p>Hello</p>
    <example [test]="someAttr"
      [hyphenated-test]="someHyphenatedAttr"
      [alias-test]="someAlias"></example>
    `,
  directives: [Example]
})
class App {
  constructor() {
    this.someAttr = "attribute passsed to component";
    this.someHyphenatedAttr = "hyphenated attribute passed to component";
    this.someAlias = "attribute passed to component then aliased";
  }
}

bootstrap(App);

/client/example.ts

import {Component, View, Attribute} from 'angular2/angular2';

@Component({
  selector: 'example',
  properties: ['test', 'hyphenatedTest', 'alias: aliasTest']
})
@View({
  template: `
    <p>Test: {{test}}</p>
    <!-- result: attribute passsed to component -->
    <p>Hyphenated: {{hyphenatedTest}}</p>
    <!-- result: hyphenated attribute passed to component -->
    <p>Aliased: {{alias}}</p>
    <!-- result: attribute passed to component then aliased -->

    <button (click)="attributeCheck()">What is the value of 'this.test'?</button>
    <!-- result: attribute passed to component -->
  `
})
/*******************************************************************
* HERE IS THE PROBLEM. How to access the attribute inside the class? 
*******************************************************************/
export class Example {
  constructor(@Attribute('test') test:string) {
     console.log(this.test); // result: undefined
     console.log(test); // result: null
  }
  attributeCheck() {
    alert(this.test);
  }
}

To sum up:

Is it possible to retrieve an attribute within the child component's class that was provided by the parent component?

Repository Link

Answer №1

Updated to beta.1

If you're looking for a way to initialize data in Angular, you can utilize the ngOnInit method.

@Component({
  selector: 'example',
  inputs: ['test', 'hyphenatedTest', 'alias: aliasTest'],
  template: `
    <p>Test: {{test}}</p>
    <!-- result: attribute passed to component -->
    <p>Hyphenated: {{hyphenatedTest}}</p>
    <!-- result: hyphenated attribute passed to component -->
    <p>Aliased: {{alias}}</p>
    <!-- result: attribute passed to component then aliased -->

    <button (click)="attributeCheck()">What is the value of 'this.test'?</button>
    <!-- result: attribute passed to component -->
  `
})
export class Example {

  ngOnInit() {
    console.log(this.test);
    this.attributeCheck();
  }

  attributeCheck() {
    alert(this.test);
  }
}

Answer №2

To access property values in a child component, you can follow these steps:

import {Component, View, Attribute} from 'angular2/angular2';

@Component({
  selector: 'example',
  properties: ['test', 'hyphenatedTest', 'alias: aliasTest']
})
@View({
  template: `
    <p>Test: {{_test}}</p>
    <!-- result: attribute passed to component -->
    <p>Hyphenated: {{_hyphenatedTest}}</p>
    <!-- result: hyphenated attribute passed to component -->
    <p>Aliased: {{_alias}}</p>
    <!-- result: attribute passed to component then aliased -->
  `
})
export class Example {
  _test: string;
  _hyphenatedTest: any; //change to proper type
  _alias: any; //change to proper type

  constructor() {
  }

  set test(test) {
    this._test = test;
  }

  set hyphenatedTest(hyphenatedTest) {
    this._hyphenatedTest = hyphenatedTest;
  }

 set alias(alias) {
    this._alias = alias;
  }

}

The set method is executed when the property value changes. The value is then passed to a local variable in the component for further manipulation.

Key points to remember:

  • The set method always runs after the constructor
  • The parameter name in the set method must match the method's name and the property's name

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

Completion of TypeScript code is not working as expected, the variable that is dependent upon is not

Looking for assistance with creating code completion in TypeScript. Variable.Append1 Variable.Append2 Variable.Append3 I have defined the following class: class Variable { Append1(name: string){ if (name == undefined) ...

Converting an integer into a String Enum in TypeScript can result in an undefined value being returned

Issue with Mapping Integer to Enum in TypeScript export enum MyEnum { Unknown = 'Unknown', SomeValue = 'SomeValue', SomeOtherValue = 'SomeOtherValue', } Recently, I encountered a problem with mapping integer val ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...

Creating custom functionality by redefining methods in Typescript

My current scenario is as follows: abstract class A implements OnInit{ ngOnInit() { this.method(); } private method() { // carrying out tasks } } class B extends class A implements OnInit { ngOnInit() { thi ...

What could be the reason for TypeScript throwing an error that 'product' does not exist in type '{...}' even though 'product' is present?

Structure of Prisma Models: model Product { id String @id @default(auto()) @map("_id") @db.ObjectId name String description String price Float image String createdAt DateTime @default(now()) updatedAt Da ...

Unable to interact with the page while executing printing functionality in

component: <div class="container" id="customComponent1"> New Content </div> <div class="container" id="customComponent2"> different content </div> ...

What is the process for running Protractor in a project that is not using AngularCLI?

I am new to using Protractor and I am eager to run my first test. However, I am facing some difficulties on how to get started. I initially tried entering ng e2e in the cmd prompt but received a message stating that I "have to be inside an Angular CLI proj ...

How to remove the footer on a particular webpage

I am currently using angular version 14. On a specific page, there is a footer visible that I wish to hide. This page pertains to job search, and I would like to remove or conceal the footer specifically from this job search page. The footer has been separ ...

Utilize a single component across various instances for enhanced efficiency

After thorough research, I couldn't find a solution to my problem despite similar questions being asked. I've developed an angular component for styled radio buttons and need to use it multiple times on different instances. To get a better unde ...

Type narrowing not functioning as expected based on the specific data types

I've encountered an issue with type narrowing in my code that is leading to a compiler error. Strangely, making subtle changes to the types involved allows the compiler to pass without errors. These types have some overlap and include optional attribu ...

The NX monorepo from @nrwl is unable to locate the .svgr configuration file within the lib directory

Recently, I started working with NX Monorepo that consists of 2 separate react applications. In order to share icons between these apps, I decided to create an icons library. I made changes to the project.json file of the icons library and added a svg com ...

How can I rename an event function in Angular 2?

Is it possible to dynamically change the function associated with an event? I attempted to do so like this: (click) = "{{myFunction}}" However, I encountered an error stating "Parser Error: Got interpolation ({{}}) where expression was expected". I am lo ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

Revamping HTML with AngularJS Directive: Enhancing the Layout with New Angular Attributes

I am currently facing an issue with the compiler not recognizing a new attribute I have added in a directive. In my Angular TypeScript code, I have the following setup: public class MyDirectiveScope: ng.IScope { foo: boolean; } public class MyDirecti ...

Angular HTTP Interceptor encountering issue with TypeError: (0 , x.fromPromise) function is not recognized

I have implemented the following code snippet to attach reCAPTCHA v3 to an HTTP Request: @Injectable() export class RecaptchaInterceptor implements HttpInterceptor { constructor(private recaptchaService: ReCaptchaService) { } intercept(httpRequest: HttpRe ...

Retrieving the key from an object using an indexed signature in Typescript

I have a TypeScript module where I am importing a specific type and function: type Attributes = { [key: string]: number; }; function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any { // ... } Unfortunately, I am unab ...

React Hot Toast useState is unfortunately not exported from the React library

While working on a Next.js project, I encountered an issue when trying to use react-hot-toast. When I attempted to import it into any file, I received the following error message: Error - ./node_modules/react-hot-toast/dist/index.mjs Attempted import erro ...

What's the best way to implement satisfies with a generic type?

In my development process, I am working with components that have default values combined with props. To streamline this process, I created a single function for all components: export function getAssignProps <T extends {}>(propsMass:T[]){ return ...

Error: Unable to convert null or undefined to an object | NextAuth

Recently, I've been attempting to implement a SignIn feature with Nextauth using the following code: import { getProviders, signIn as SignIntoProvider} from "next-auth/react"; function signIn({ providers }) { return ( <> ...

Obtain the total number of requests submitted by the user within a 24-hour period

I have a POST request point in my API where I need to track and store all work journals made by a worker. export const registerPoint = async (req: Request, res: Response) => { const user = res.locals.decoded; const {id} = user; const point = new Point ...