Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to custom component

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?

like image 730
rpayanm Avatar asked Feb 17 '17 00:02

rpayanm


People also ask

How do you pass variables into components?

There are two ways to pass data into a component, with 'property binding' and 'event binding'. In Angular, data and event change detection happens top-down from parent to children. However for Angular events we can use the DOM event mental model where events flow bottom-up from child to parent.

How do you pass a prop in component Angular?

Note that when using the [] notation in an Angular template, Angular will expect an expression to be passed. To pass a string directly, as we're doing here, we wrap them in single-quotes. In addition to passing the URL of the image as a prop, we've also been passing a class name.


2 Answers

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.

like image 188
Stefan Svrkota Avatar answered Sep 20 '22 21:09

Stefan Svrkota


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.

like image 42
Garth Mason Avatar answered Sep 21 '22 21:09

Garth Mason