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

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

I used @input for a parent for a child that works great.

What will I use to create a child for the parent?

This is my compiler error I get:

enter image description here

+4
source share
1 answer

You can use @Outputto trigger events from a child component. Parent can register processing on them.

Here is an example

@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 $eventcontains the value 'some value'.

, Angular2 :

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

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

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

:

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

Edit

, .

( ).

. :

:

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

:

+4

Source: https://habr.com/ru/post/1627026/


All Articles