如何观察ng含量中输入元素的变化 [英] How to observe input element changes in ng-content
本文介绍了如何观察ng含量中输入元素的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当子组件观察到输入更改时如何调用父组件的功能?
How to call parent component's function when child component observed input changes?
下面是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
元素. - 输入
input
元素后,在TextboxComponent中发出一个事件. - 不想使
input
元素具有更多属性,例如<input type="text" (input)="event()">
.
- TextboxComponent has
ng-content
and need to projectinput
element to it. - Emit an event in TextboxComponent when
input
element is inputted something. - Don't wanna make
input
element to have more attributes, e.g.<input type="text" (input)="event()">
.
我正在编写代码,但找不到解决方案...
I was writing code, but cannot find a solution...
# 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...
});
}
}
推荐答案
input
事件正在冒泡,可以在父组件上监听
The input
event is bubbling and can be listened on the parent component
<div class="textbox-wrapper" (input)="inputChanged($event)">
<ng-content></ng-content>
</div>
这篇关于如何观察ng含量中输入元素的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文