4

Angular 2 - how can a child component speak to a parent component?

I used @input for parent to child which works fine.

What would I use to do child to parent?

This is my compiler error I get:

enter image description here

AngularM
  • 15,982
  • 28
  • 94
  • 169
  • Can't believe Angular2 make this thing so complex. It's one of the most important features on a component-based approach, still it looks painfully counter-intuitive and cumbersome. – Aurelio Jul 10 '16 at 11:40

1 Answers1

5

You can use @Output to trigger events from the child component. The parent one can register processing on them.

Here is a sample

@Component({
  selector: 'child',
  (...)
})
export class ChildComponent {
  @Output()
  someEvent: EventEmitter;

  constructor() {
    this.someEvent = new EventEmitter();
  }

  triggerEvent() {
    this.someEvent.emit('some value');
  }
}

and its use in the parent component:

<child (some-event)="printValue($event)"></child>

FYI $event contains the value 'some value'.

You can notice that Angular2 supports two-way binding at this level:

@Component({
  selector: 'child',
  (...)
})
export class ChildComponent {
  @Input()
  value:string
  @Output()
  valueChanges: EventEmitter;

  constructor() {
    this.valueChanges = new EventEmitter();
  }

  triggerUpdated() {
    this.valueChanges.emit('some value');
  }
}

and its use in the parent component:

<child [(value)]="someVar"></child>

Edit

To call a method from the parent component, you need to inject it into the child one.

You need to be careful at this level to cyclic dependency in imports and that hoisting isn't supported for classes (use a class before it's created).

See this answer for more details:

Here is a sample:

@Component({
  selector: 'child',
  (...)
})
export class ChildComponent {
  constructor(@Inject(forwardRef(() => AppComponent)) parent:ParentComponent) {
    (...)
  }
}

This article could also give you some hints:

Thierry

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360