angular – 如何观察ng-content中的输入元素变化

前端之家收集整理的这篇文章主要介绍了angular – 如何观察ng-content中的输入元素变化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在子组件观察到输入变化时调用父组件的功能

以下是HTML结构.

  1. # app.comopnent.html
  2. <form>
  3. <textBox>
  4. <input type="text">
  5. </textBox>
  6. </form>
  7.  
  8. # textBox.component.html
  9. <div class="textBox-wrapper">
  10. <ng-content>
  11. </div>

限制如下.

> TextBoxComponent具有ng-content,需要将input元素投影到它.
>输入输入元素时,在TextBoxComponent中发出一个事件.
>不要让输入元素具有更多属性,例如< input type =“text”(input)=“event()”>.

我在编写代码,但找不到解决方案……

  1. # input.directive.ts
  2. @Directive({ selector: 'input',... })
  3. export class InputDirective {
  4. ngOnChanges(): void {
  5. // ngOnChanges() can observe only properties defined from @Input Decorator...
  6. }
  7. }
  8.  
  9. # textBox.component.ts
  10. @Component({ selector: 'textBox',... })
  11. export class TextBoxComponent {
  12. @ContentChildren(InputDirective) inputs: QueryList<InputDirective>;
  13. ngAfterContentInit(): void {
  14. this.inputs.changes.subscribe((): void => {
  15. // QueryList has a changes property,it can observe changes when the component add/remove.
  16. // But cannot observe input changes...
  17. });
  18. }
  19. }
输入事件是冒泡的,可以在父组件上进行侦听
  1. <div class="textBox-wrapper" (input)="inputChanged($event)">
  2. <ng-content></ng-content>
  3. </div>

Plunker example

猜你在找的Angularjs相关文章