Angular2 Communication Between Components

515 views Asked by At

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

1

There are 1 answers

1
corsaro On

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