IntoTheDeep
IntoTheDeep

Reputation: 4118

Angular 2 Pass string argument to component

My target is to pass string arguments to component. Example: I have component that holds and show title and subtitle. I want to pass that strings when I am setting the selector. Something like:

@Component({
    selector: 'title-subtitle',
})

in html:

<title-subtitle title="My title" subtitle="My subtitle"></title-subtitle>

Upvotes: 2

Views: 9693

Answers (3)

mrtpk
mrtpk

Reputation: 1437

To pass a string using @input from a parent component to child component there are two ways.

If you want to pass the string,

<child-component childInput="child input"> </child-component>

If you want to pass the variable from parent component to child component,

<child-component [childInput]="parentInput"> </child-component>

Upvotes: 5

Alex Beugnet
Alex Beugnet

Reputation: 4071

Parent component :

<title-subtitle [childInput]="parentInput">
</title-subtitle>

private parentInput: any;

ngOnInit() {
    this.parentInput = 'Hello World';
}

Child component :

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

export class ChildComponent implements OnChanges, OnInit {
  @Input() private childInput: any;

  ngOnInit() {
    // When the data is passed instantly, you can access it here.
    // You can also use {{childInput}} in your HTML
    console.log(this.childInput);
  }

  ngOnChanges(changes) {
    // When the data is async : get the changes when they are ready

    // Get @Input data when it's ready
    if (changes.childInput) {      
       console.log(changes.childInput.currentValue);
    }
  }
}

Note the naming of the properties in the parent HTML.

N.B : You only need the OnInit and/or OnChanges events when you actually need to do something with your data (i.e. Deep cloning it, ...). If you only display it in your HTML with interpolation, there is no need for the events.

N.B 2 : Be aware that this is the SAME OBJECT (same reference) that is sent to your child, which means that if you update a property of your object in your ChildComponent, the changes will also affect the parent. Usually you clone your object to avoid that kind of behavior in the OnInit or OnChanges events.

Upvotes: 3

Jinex2014
Jinex2014

Reputation: 342

If you review this Hero example it should answer your question

Pay attention to

<my-hero-detail [hero]="selectedHero"></my-hero-detail>

on the app.component.ts file

Upvotes: 0

Related Questions