Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 pass attribute to class constructor

How do I pass attributes from a parent component to their child components' class constructor in Angular 2?

Half of the mystery is figured out, as attributes can be passed to the view without problem.

/client/app.ts

import {Component, View, bootstrap} from 'angular2/angular2';
import {Example} from 'client/example';

@Component({
  selector: 'app'
})
@View({
  template: `<p>Hello</p>
    <example [test]="someAttr"
      [hyphenated-test]="someHyphenatedAttr"
      [alias-test]="someAlias"></example>
    `,
  directives: [Example]
})
class App {
  constructor() {
    this.someAttr = "attribute passsed to component";
    this.someHyphenatedAttr = "hyphenated attribute passed to component";
    this.someAlias = "attribute passed to component then aliased";
  }
}

bootstrap(App);

/client/example.ts

import {Component, View, Attribute} from 'angular2/angular2';

@Component({
  selector: 'example',
  properties: ['test', 'hyphenatedTest', 'alias: aliasTest']
})
@View({
  template: `
    <p>Test: {{test}}</p>
    <!-- result: attribute passsed to component -->
    <p>Hyphenated: {{hyphenatedTest}}</p>
    <!-- result: hyphenated attribute passed to component -->
    <p>Aliased: {{alias}}</p>
    <!-- result: attribute passed to component then aliased -->

    <button (click)="attributeCheck()">What is the value of 'this.test'?</button>
    <!-- result: attribute passed to component -->
  `
})
/*******************************************************************
* HERE IS THE PROBLEM. How to access the attribute inside the class? 
*******************************************************************/
export class Example {
  constructor(@Attribute('test') test:string) {
     console.log(this.test); // result: undefined
     console.log(test); // result: null
  }
  attributeCheck() {
    alert(this.test);
  }
}

To re-iterate:

How can I access an attribute inside the child component's class passed in from the parent component?

Repo

like image 939
shmck Avatar asked Aug 05 '15 10:08

shmck


Video Answer


1 Answers

Updated to beta.1

You can use ngOnInit for this

@Component({
  selector: 'example',
  inputs: ['test', 'hyphenatedTest', 'alias: aliasTest'],
  template: `
    <p>Test: {{test}}</p>
    <!-- result: attribute passsed to component -->
    <p>Hyphenated: {{hyphenatedTest}}</p>
    <!-- result: hyphenated attribute passed to component -->
    <p>Aliased: {{alias}}</p>
    <!-- result: attribute passed to component then aliased -->

    <button (click)="attributeCheck()">What is the value of 'this.test'?</button>
    <!-- result: attribute passed to component -->
  `
})
export class Example {

  ngOnInit() {
    console.log(this.test);
    this.attributeCheck();
  }

  attributeCheck() {
    alert(this.test);
  }
}
like image 113
Eric Martinez Avatar answered Sep 23 '22 10:09

Eric Martinez