0

When we call a component in Angular 2 like so <my-component></my-component>. Is it possible to pass in attrs here so that they can be used within the component class?

example:

<my-component data-is-live="true"></my-component>

// class
export class MyComponent {
    constructor() {
        console.log($attrs);
    }
} 
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
John williams
  • 654
  • 1
  • 8
  • 22
  • Please read [ask]. Key phrases: "Search, and research" and "Explain ... any difficulties that have prevented you from solving it yourself". – Heretic Monkey Dec 14 '16 at 18:02
  • Possible duplicate of [Angular 2 external inputs](http://stackoverflow.com/questions/33152914/angular-2-external-inputs) – Heretic Monkey Dec 14 '16 at 18:13
  • http://stackoverflow.com/questions/39614451/angular-2-input-binding-does-not-work/39614592#39614592 – yurzui Dec 14 '16 at 19:09

2 Answers2

1

You can by simply specifying it as an input parameter:

@Component({
    selector: 'my-component',
    template: `
    <p>Is it live: {{isLive}} </p>
  `
})
export class MyComponent {
    @Input('is-live') isLive: string;

    ngOnInit() {
        console.debug(this.isLive);
    }
}

See this plunkr: http://plnkr.co/edit/2E6XcNW6cTOblyhBOEwI?p=preview

Note

You can't use an attribute starting with data-, Angular2 seems to ignore those.

Robba
  • 7,684
  • 12
  • 48
  • 76
-1

Yes, you can pass data between components (from parent to child for example) Here's a link with the different ways : official doc Hope that helps u :)

Mourad Idrissi
  • 3,455
  • 5
  • 17
  • 29
  • That didn't answer my question, nowhere on that page illustrates how to do what i want to do. – John williams Dec 14 '16 at 18:01
  • @Johnwilliams the `@Input()` decorator is covered in that documentation, while the answer is not great (borderline just a link) it did in fact contain the solution you ended up accepting! – silentsod Dec 14 '16 at 18:13
  • Life is hard at times, i suggest you take it on the chin and just move on. – John williams Dec 14 '16 at 18:14
  • There are multiple solutions, I gave u the right link to choose the easy answer for u ;) You were going to make a little effort to find what @Robba wrote, m8 – Mourad Idrissi Dec 14 '16 at 20:19