Угловой родительский компонент, слушающий дочерний компонент ng - PullRequest
0 голосов
/ 01 ноября 2018

Я хочу, чтобы функция вызывала внутри моего родительского компонента, когда мой дочерний компонент генерирует событие. Дочерний компонент передается в родительский элемент через ng-content. Я упростил код того, что я пытаюсь сделать, но у меня не получается, чтобы ребенок передавал родителю. Я хочу передать дочерний элемент с помощью ng-content, потому что дочерний компонент может состоять из множества компонентов, а не одного отдельного компонента

Пример:

main.ts

<parent-component>
  <child-component></child-component>
</parent-component>

parent.component.ts

<div>
 {{ this.value }}
 <ng-content (updated)="updateParentValue()"></ng-content> <-- this doesn't work
</div>

updateParentValue(value) {
  this.value = value;
}

child.component.ts

<div>
  <span (click)="updateStuff()">update</span>
</div>

@Output() updated = new EventEmitter();

updateStuff() {
  // Stuff
  this.updated.emit(this.value);
}

1 Ответ

0 голосов
/ 02 ноября 2018

Спасибо, Крым, решил эту ссылку

main.ts

<parent-component>
  <child-component></child-component>
</parent-component>

parent.component.ts

<div>
 {{ this.value }}
 <ng-content></ng-content>
</div>

@ContentChildren(ChildComponent) childComponents: QueryList<ChildComponent>;

ngAfterViewInit() {
   this.childComponents.forEach((childComponent: ChildComponent) => {
       childComponent.updated.subscribe((item) => this.updateParentValue(item));           
   });
}

updateParentValue(value) {
  this.value = value;
}

child.component.ts

<div>
  <span (click)="updateStuff()">update</span>
</div>

@Output() updated = new EventEmitter();

updateStuff() {
  // Stuff
  this.updated.emit(this.value);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...