如何在子组件观察到输入变化时调用父组件的功能?
以下是HTML结构.
# app.comopnent.html <form> <textBox> <input type="text"> </textBox> </form> # textBox.component.html <div class="textBox-wrapper"> <ng-content> </div>
限制如下.
> TextBoxComponent具有ng-content,需要将input元素投影到它.
>输入输入元素时,在TextBoxComponent中发出一个事件.
>不要让输入元素具有更多属性,例如< input type =“text”(input)=“event()”>.
# input.directive.ts @Directive({ selector: 'input',... }) export class InputDirective { ngOnChanges(): void { // ngOnChanges() can observe only properties defined from @Input Decorator... } } # textBox.component.ts @Component({ selector: 'textBox',... }) export class TextBoxComponent { @ContentChildren(InputDirective) inputs: QueryList<InputDirective>; ngAfterContentInit(): void { this.inputs.changes.subscribe((): void => { // QueryList has a changes property,it can observe changes when the component add/remove. // But cannot observe input changes... }); } }
输入事件是冒泡的,可以在父组件上进行侦听
原文链接:https://www.f2er.com/angularjs/142293.html<div class="textBox-wrapper" (input)="inputChanged($event)"> <ng-content></ng-content> </div>