Basil Joy
Basil Joy

Reputation: 181

view not updated while changing class variable value angular2

I have a component which has a variable myName

export class ConversationComponent implements OnInit {
  private myName: string;

  showNames(name)
  {
    this.myName=name;
  }
}

the value is set by using showNames(),and it is displayed by

 <h4>{{MyName}} </h4>

but when the value is set to the variable the change is not reflected in the view ie html page.

Here's my Service:

import { Injectable } from '@angular/core'; 
import { ConversationComponent } from './conversation/conversation.component'; 

@Injectable() export class ChatingService { 

  constructor(private Conversation:ConversationComponent) { } 

  setValue(val) { 
    this.Conversation.showNames(this.myValue); 
  } 
}

Upvotes: 0

Views: 533

Answers (2)

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

Reputation: 657937

Injecting a component into a service doesn't work. You need a different approach. You probably injected a component class instance that is not related in any way to the component shown on the page.

Upvotes: 1

V&#252;sal
V&#252;sal

Reputation: 2706

Try this:

@Component(...)
export class ConversationComponent implements OnInit {
  private myName: string;

  constructor(private service:ServiceClass) {}

  ngOnInit() {
    this.showNames(this.service.getName());
  }

  showNames(name) {
    this.myName=name;
  }
}

Here ServiceClass is your injectable Service.

Upvotes: 0

Related Questions