【问题标题】:Angular 5 Component - How Can i get all inputs inside the contentAngular 5 Component - 我如何获取内容中的所有输入
【发布时间】:2018-05-16 01:13:20
【问题描述】:

我正在开发一个组件,我想实现一个函数,该函数将焦点放在它的 ng-content 中的第一个输入元素。

所以我粗略地尝试了这个他遵循模板代码并尝试使用 ViewChildren 和 ContentChildren。

@Component({
  selector: '[my-component]', // tslint:disable-line
  template: `<div class="my-container">
        <ng-content></ng-content>
      </div>`
})
export class MyComponent implements AfterViewInit, OnDestroy {

  @ViewChildren('input') vc;
  @ContentChildren('input', {descendants: true}) cc;

  ngAfterViewInit() {
    //Nothing in either QueryList ???
    console.log(this.vc, this.cc);
  }

  focus () {
    //Nothing in either QueryList ???
    this.vc.first.nativeElement.focus();
  }
}

在模板/页面中使用该组件时,它大致如下所示:

<div my-component>
  <div class="field"><input></div>
  <div class="field"><input></div>
  <div class="field"><input></div>
  <div class="field"><input></div>
  <div class="field"><input></div>
</div>

同样,我想要的是获取所有出现在内容中的输入元素,并且它们也可以隐藏在 div 和包装器中。似乎 ContentChildren 应该是正确的,但它没有返回任何元素。即 QueryList.results 为空。

我做错了什么或如何在内容区域内获取输入?

【问题讨论】:

    标签: angular angular-components


    【解决方案1】:

    @ViewChildren 装饰器支持指令或组件类型作为参数。还支持模板变量的名称,即#ref 定义。所以我相信如果你举个例子,它会起作用

    <div my-component>
      <div class="field"><input #myInput></div>
      <div class="field"><input #myInput></div>
      <div class="field"><input #myInput></div>
      <div class="field"><input #myInput></div>
      <div class="field"><input #myInput></div>
    </div>
    

    然后

    @ViewChildren('myInput') vc;
    

    【讨论】:

    • 我们不能在同一个 html 中多次使用同一个 #ref 标签。 ```错误:模板解析错误:引用“#input”被定义了多次```
    猜你喜欢
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 2014-09-06
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多