Rodman Swanston Rodman Swanston - 11 days ago 8
TypeScript Question

angular 2 child reference to variable into parent

How to change the value of a variable or use a method in a parent component from a child component without using input and output

I try something like this but not working.

@Component({
selector: 'child',
template: `
<div>
<h2>{{name}}</h2>
<button (click) = "rename()" > Rename Parent </button>
</div>
`,
})
export class Child {
name:string;
constructor() {
this.name = 'child'
}

rename() {
App.name = 'Rename';
}

}

@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<child> </child>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}


example here

plunker example

Answer

Input and Output are just made for this. It is, according to the Angular2 Documentation, made for communication between parent and child components.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <child [name]="this.name" (nameChanged)="this.name = $event"> </child>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

@Component({
  selector: 'child',
  template: `
    <div>
      <h2>{{name}}</h2>
      <button (click) = "rename()" > Rename Parent </button>
    </div>
  `,
})
export class Child {

@Input() name:string;
@Output() nameChanged: EventEmitter<string> = new EventEmitter<string>();

  constructor() {
  }

  rename() {
    this.nameChanged.emit('Renamed');
  }

}

Alternatively you could inject a service into both parent and child component, which has some values that both parent and child can access and modify. But make sure to add that service to either only the parent component or only the AppModule, otherwise you would get 2 instances of your service.