0

I search about communication between components with Angular2 i try in this mode but doesn t work

the template variantpages.component.html content this

<button (click)="changetext()">Change</button> 
<child></child>



@Component({
  selector: 'menu-left',
  templateUrl: './app/pages/variantpages.component.html'
})

export class AppComponent{


child = new ChildComponent();


 changetext(){ this.child.changetext2()}

}
@Component({
   selector: 'child',
   template: `<p>page of {{ pageCount }}</p>`
})

export class ChildComponent{

@Input() photo:string = "ciao ciao";

@Output() valueChange = new EventEmitter();


pageCount:number;
constructor(){ this.pageCount = 0; }

changetext2(){
        this.pageCount++;
        this.valueChange.emit(this.pageCount);
        console.log(this.pageCount);
  }
}

so the console log show the increment number but pageCount stay a 0

Thanks

corsaro
  • 731
  • 1
  • 9
  • 24
  • what does your html contains update it to post – Aravind Apr 09 '17 at 18:15
  • 1
    Without looking too closely (meaning there could be other problems as well), but noticed the following... Check *"parent listens for child event"* and the correct use of output in this link: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child Make notice of the childtag in that example. Hint: `` is not enough ;) And use `@ViewChild` instead of `child = new ChildComponent();` The link I provided addresses both issues ;) – AT82 Apr 09 '17 at 18:50
  • hi thanks for answer i put the part of html, the problem is the component call the method changetext2 and i see the increment in the console but dont change in the page – corsaro Apr 10 '17 at 07:59
  • First of all you should use ViewChild (check the link I gave you). If the problem still persists, please provide a plunker. – AT82 Apr 10 '17 at 18:02

1 Answers1

0

ok i solved with EventEmitter but this work only from parent and children, now my question it s different, if i have two different component and i want with one button (click) in component A to change the string in a Component B, i call this method setName

COMPONENT A

constructor(private appComponent: AppComponent ){ }
setName(newName: string) {
        this.appComponent.name = newName;
        console.log(this.name);
      }

COMPONENT B

@Input() name: string = "Angular3"

the console show the new string, but the name don't change

corsaro
  • 731
  • 1
  • 9
  • 24
  • You can use a shared service class for this type of communication. See: https://angular.io/docs/ts/latest/cookbook/component-communication.html for more information – Brandon Taylor Apr 13 '17 at 12:50