Pass variable to custom component

AngularTypescriptAngular2 TemplateAngular2 Components

Angular Problem Overview


I have my custom component:

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

I can use it like this:

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

But how I can pass a variable? For example:

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

And use this in my component code?

Angular Solutions


Solution 1 - Angular

You need to add Input property to your component and then use property binding to pass 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);
    }
}

And in your template:

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

For more info, check out this page.

Solution 2 - Angular

You can add an @Input() decorator to a property on your component.

export class MyCustomComponent {
    constructor() {
        console.log('myCustomComponent');
    }

    @Input() title: string;
}


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

or binding title from a variable 'theTitle'

<my-custom-component [title]="theTitle"></my-custom-component>

See the @Input()decorator documentation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrpayanmView Question on Stackoverflow
Solution 1 - AngularStefan SvrkotaView Answer on Stackoverflow
Solution 2 - AngularGarth MasonView Answer on Stackoverflow