Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding properties from service to component Angular 4

Tags:

angular

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.

like image 428
Menahem Gil Avatar asked May 04 '26 23:05

Menahem Gil


1 Answers

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> 
like image 149
Surjeet Bhadauriya Avatar answered May 07 '26 12:05

Surjeet Bhadauriya