Pass variable to custom component

rpayanm picture rpayanm · Feb 17, 2017 · Viewed 71.5k times · Source

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?

Answer

Stefan Svrkota picture Stefan Svrkota · Feb 17, 2017

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.