3

I have a component which I inject a service. I try to bind the properties from the service to the component's html view.

I tried just to bind in a regular way <p>{{a}}</p> but it didn't work. I asked here and the answer I got was to refer to the service name first:

service:

export class MyService {
    a: string = 'Hello world'; 
    b: number = 1;

    c(): number {
      this.b += 1;
      return this.b;
}
}

component.ts:

export class myComponent {
constructor(public myService: MyService){}
}

component.html:

<p>{{myService.a}}</p>

I did it and still doesn't work - what do I miss?

If I console the properties in the service methods, then call the method in the component class, it will console the properties. But once I try to bind them in the template - it's doesn't work.

Thanks.

2
  • create a variable, assign the a property in the constructor, bind this variable to your <p> tag in the html Commented Jul 5, 2018 at 14:44
  • Ok, thanks. So you mean that I need to create a variable in the component class and assign to this variable the property from the service? Commented Jul 5, 2018 at 14:59

1 Answer 1

2

You injected the service and you are getting value from service. But but but.. you didn't assign it to your this.

So just you need to assign your value to this variable.

See below:

myComponent.component.ts

export class myComponent {
  constructor(public myService: MyService){}
  a: any = myService.a;
}

Now you can get this variable into HTML.

my.html

<p>{{a}}</p> 
Sign up to request clarification or add additional context in comments.

2 Comments

Ok!! Thanks thanks thanks. I was assuming that once I inject it it's available. Apparently as you say I need to assign it. Thanks again.
Pleasure..!! Keep asking..!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.