加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:32:02 所属栏目:安全 来源:网络整理
导读:如何在子组件观察到输入变化时调用父组件的功能? 以下是HTML结构. # app.comopnent.htmlform textbox input type="text" /textbox/form# textbox.component.htmldiv class="textbox-wrapper" ng-content/div 限制如下. TextboxComponent具有ng-content,需要
如何在子组件观察到输入变化时调用父组件的功能?

以下是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...
    });
  }
}
输入事件是冒泡的,可以在父组件上进行侦听
<div class="textbox-wrapper" (input)="inputChanged($event)">
  <ng-content></ng-content>
</div>

Plunker example

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读