user2243952
user2243952

Reputation: 277

calling variables from typescript file in html template [angular]

I just started working with angular after reading the docs. I'm still a newbie.

Calling arrays in angular2 is simple:

you just have to use *ngfor item of items and then {{item.name}}.

what if I'm calling a single object, string or any, from my ts file . How can I do that?

I tried :

{{myvariable}} 

or

<div  ng-init="let x = myvariable">   {{x.name}}</div> 

and other stuff but it doesn't work. Thanks in advance.

Upvotes: 3

Views: 27050

Answers (2)

Abhay
Abhay

Reputation: 483

the variable you are trying to access in your template should be available as public property on your component. e.g. in your component if you have myvar as public property with statement like public myvar : any; and then some where in life cycle hooks or other method of component if you assign that to an object e.g. in ngOnInit if you do this.myvar = { p1 : 2 } then you can access properties of myvar in your template like {{myvar.p1}}

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657078

{{myvariable.id}} {{myvariable.name}}

or if the variable is not initialized yet when the component is created.

{{myvariable?.id}} {{myvariable?.name}}

Upvotes: 4

Related Questions