Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  125] [ 6]  / answers: 1 / hits: 108480  / 9 Years ago, sun, october 25, 2015, 12:00:00

I am stuck on trying to pass a property value into my component. From what I've read everything looks correct. But it is still not working. My test value gets output to the screen and the console as null. :(



This is my test component:



import {Component, Input} from 'angular2/angular2';

@Component({
selector: 'TestCmp',
template: `Test Value : {{test}}`
})

export class TestCmp {

@Input() test: string;

constructor()
{
console.log('This if the value for user-id: ' + this.test);
}
}


This is how I am calling the component from the parent page.



<TestCmp [test]='Blue32'></TestCmp>


When the page render's the test value is empty. I only see 'Test Value :'.



Instead of 'Test Value : Blue32'.


More From » angular

 Answers
11

You have four things that I can note :




  • You are passing an input in the root component, which will not work.

  • As @alexpods mentioned, you are using CamelCase. You should not.

  • You are passing an expression instead of an string through [test]. That means that angular2 is looking for a variable named Blue32 instead of passing a raw string.

  • You are using the constructor. That will not work, it must be after the view has been initialized data-bound properties have been initialized (see docs for OnInit).



So with a few fixes it should work



Example updated to beta 1



import {Component, Input} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

@Component({
selector : 'childcmp',
template: `Test Value : {{test}}`
})
class ChildCmp {
@Input() test: string;
ngOnInit() {
console.log('This if the value for user-id: ' + this.test);
}
}

@Component({
selector: 'testcmp',
template : `<childcmp [test]='Blue32'></childcmp>`
directives : [ChildCmp]
})
export class TestCmp {}

bootstrap(TestCmp);


See this plnkr as an example.



Update



I see that people still reach this answer, so I've updated the plnkr to beta 1 and I corrected one point on the explanation : You can access inputs in ngAfterViewInit, but you can access them earlier in the lifecycle within ngOnInit.


[#64610] Thursday, October 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haleeg

Total Points: 703
Total Questions: 100
Total Answers: 98

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
haleeg questions
Thu, Oct 7, 21, 00:00, 3 Years ago
Sat, Jul 24, 21, 00:00, 3 Years ago
Mon, Sep 7, 20, 00:00, 4 Years ago
;