Sending a variable to a personalized component

I have created a unique custom component:

@Component({
    selector: 'my-custom-component',
    templateUrl: './my-custom-component.html',
    styleUrls: ['./my-custom-component.css']
})
export class MyCustomComponent {
    constructor() {
        console.log('myCustomComponent');
    }
}

To use this custom component, you can do the following:

<my-custom-component></my-custom-component>

However, the question arises on how to pass a variable. For instance:

<my-custom-component custom-title="My Title"></my-custom-component>

How can this custom title be utilized in the component code?

Answer №1

It is essential to include the Input property in your component and utilize property binding to transfer a value to it:

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

@Component({
    selector: 'my-custom-component',
    templateUrl: './my-custom-component.html',
    styleUrls: ['./my-custom-component.css']
})
export class MyCustomComponent {

    @Input()
    customTitle: string;

    constructor() {
        console.log('myCustomComponent');
    }

    ngOnInit() {
        console.log(this.customTitle);
    }
}

Incorporate this code into your template:

<my-custom-component [customTitle]="yourVariable"></my-custom-component>

To further explore this topic, refer to this resource.

Answer №2

One way to enhance your component is by utilizing the @Input() decorator for a specific property.

export class EnhancedComponent {
    constructor() {
        console.log('Enhanced Component Initialized');
    }

    @Input() description: string;
}


<enhanced-component description="Description Text"></enhanced-component>

Another option is to bind the property 'description' to a variable named 'variableDescription'

<enhanced-component [description]="variableDescription"></enhanced-component>

Refer to the official documentation on the @Input()decorator for more information.

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

Issue with `rxjs/Subject.d.ts`: The class `Subject<T>` is incorrectly extending the base class `Observable<T>`

I found a sample template code in this helpful tutorial and followed these two steps to get started - npm install // everything went smoothly, created node_modules folder with all dependencies npm start // encountered an error as shown below- node_mo ...

Implementing paper-tabs within a component in Dart's Angular 2 framework

I'm having some trouble implementing polymer paper-tabs in a dart angular2 component. Can someone point out what I might be missing in the code provided below? The paper-tabs specified in the index.html template seem to be functioning properly, but t ...

Ways to properly exit a function

What is the best way to pass the apiKey from the createUser function in User.ts to Test.ts in my specific scenario? User.ts interface User { url: string, name: string, } class User{ async createUser( user: User ):Promise<void> { le ...

Angular Material table that uses a right-to-left direction for layout

Currently, I am utilizing angular material version 7.1.1. In my setup, there is a table that has horizontal scrolling and sticky columns. Everything functions smoothly; however, when attempting to switch the display direction from right to left (as my tab ...

Angularfire2's AngularFirestoreCollection is not including keys with each object in the collection when sending data

Currently, I am working on incorporating Angularfire2 into an Angular 4 application. By utilizing AngularFirestoreCollection, I have successfully retrieved a collection of objects from my firestore. However, upon iterating through the documents in the coll ...

What is the best way to activate an <ion-datetime> with an <ion-button>?

Im currently attempting to execute the following action: I would like to select only the month and year using the example below: <ion-datetime presentation="month-year"></ion-datetime> However, I do not wish for this label to be vis ...

Automatically activate the Focus Filterfield in the ng-multiselect-dropdown upon clicking

I've integrated the ng-multiselect-dropdown package into my Angular project using this link: https://www.npmjs.com/package/ng-multiselect-dropdown. Everything is functioning as expected, but I'm looking to automatically focus on the filter input ...

Accordion A and B both require the first category of accordion A to be opened first in order for the first category of accordion B to also be

Greetings, this is my initial inquiry, please excuse any errors as English is not my first language. For my project, I am utilizing Angular 6, jQuery, and BS. I have two accordions, each with different categories: A1 and A2. My goal is for clicking on A ...

Guide to customizing CSS styles within a div element using TypeScript code in a Leaflet legend

I'm struggling to add a legend to my map using Angular 5 and typescript. I need help with setting CSS styles for the values (grades) that are displayed on the legend. Can someone guide me on where to put the styles? TS: createLegend() { let lege ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...

Issue with Framer-motion animation not triggering on exit

Here is a link to the code sandbox In this gif demonstration, it's evident that the notifications are not triggering the exit animation when removed from the DOM (usually after 6 seconds). Why is this happening? I've followed all the suggestion ...

Notifying Subscribed Angular8 Components Based on Logical Conditions with Observables Inside Services

I provide a service that offers a function returning an Observable. Within this service, I have certain logic that should trigger a new call on the Observable to update the data for subscribed components. While I can use next within the Observer construct ...

Leveraging local resources to create images with the help of @vercel/og and Next.js

Utilizing the latest @vercel/og library for generating meta-tag images has been quite intriguing. The official example showcases how to leverage images from an external source. The Quandary at Hand <img src={"https://res.cloudinary.com/iqfareez ...

Issue with Angular 18 component not being displayed or identified

Recently, I began building an Angular 18 application and encountered an issue with adding my first component as a standalone. It appears that the app is not recognizing my component properly, as it does not display when added as an HTML tag in my app.compo ...

Missing data: null or undefined?

When using vuex-module-decorators, is it better to set the default value of a data property to null or undefined? For example: export default class ComponentName extends Vue { post: BlogPost | null = null } or export default class ComponentName extends V ...

Separating React props based on multiple Typescript interfaces

Is there a way to split the props object in React based on an Typescript interface that extends multiple other interfaces? Alternatively, I could duplicate the props and pass them to components that don't need them, but that would not be the most effi ...

Emphasize the chosen row in Primeng table without needing to select the checkbox

Currently, I am utilizing the primeng library to implement a p-table combined with a p-checkbox. My goal is to enable the highlighting of a clicked row (or its content) without automatically checking the checkbox. The intention is for the Checkbox to only ...

Searching for a foolproof oauth framework that includes efficient refresh tokens

Currently, I am implementing oauth with refresh tokens for my Angular application and have a specific set of requirements: Automatically refresh the token when 5% of its time is remaining Handle situations where there is a loss of internet connection (re ...

The issue encountered is when the data from the Angular form in the login.component.html file fails to be

I am struggling with a basic login form in my Angular project. Whenever I try to submit the form data to login.components.ts, it appears empty. Here is my login.component.html: <mat-spinner *ngIf="isLoading"></mat-spinner> & ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...