【问题标题】:Why is @ViewChildren zero-length?为什么@ViewChildren 的长度为零?
【发布时间】:2018-04-14 17:02:14
【问题描述】:

followthese 实现ViewChildren,但我无法得到孩子。为什么?

@ViewChildren(TextField) inputs: QueryList<TextField>;

ngAfterViewInit(): void {
    console.log('this.inputs.length = ', this.inputs.length);
    // the length is 0
}

DEMO

【问题讨论】:

  • 无法查询TextField,尝试使用模板引用变量&lt;TextField #ref&gt;&lt;/TextField&gt;和组件@ViewChildren('ref') inputs: QueryList&lt;ElemenetRef&gt;;
  • @yurzui - 为什么我们不能查询TextField's?
  • The Angular api 查询组件类名@ViewChildren(Pane) ...
  • @ViewChildren(Pane) 正在工作,因为Pane 是类而不是选择器。在您共享的链接中,它在Metadata Properties >“选择器 - 用于查询的指令类型或名称”下说明。
  • @ConnorsFan 请参阅下面的答案

标签: angular nativescript angular2-nativescript


【解决方案1】:

在模板中添加模板变量textField(可以是任何东西)为:

<StackLayout class="home-panel">
    <TextField #textField hint="Enter text1..."></TextField>
    <TextField #textField hint="Enter text2..."></TextField>
</StackLayout>

那么这将按预期结果:

@ViewChildren('textField') inputs: QueryList<ElementRef>;

【讨论】:

    【解决方案2】:

    关于我们可以查询的内容有一个很好的答案

    所以我们可以查询匹配模板元素的角度指令,但是没有带有TextField选择器的指令。 TextField 是 nativescript 组件而不是 angular

    查询 TextValueAccessor

    只有TextValueAccessor 指令,但要查询它,您应该尊重它的选择器:

    TextField[ngModel],TextField[formControlName],TextField[formControl],
    

    例如,以下应该可以工作:

    模板

    <StackLayout class="home-panel">
        <TextField hint="Enter text1..." ngModel></TextField>
        <TextField hint="Enter text2..." ngModel></TextField>
                                         ^^^^^^^
                                     notice attribute here
    </StackLayout>
    

    component.ts

    import { TextValueAccessor } from 'nativescript-angular/forms/value-accessors';
    
    ...
    
    @ViewChildren(TextValueAccessor) inputs: QueryList<TextField>;
    

    查询元素引用

    否则使用模板引用变量:

    模板

    <TextField #ref></TextField>
    

    component.ts

    @ViewChildren('ref') inputs: QueryList<ElemenetRef>;
    

    【讨论】:

    • 这是一个详细的解释,所以我选择这个作为接受的答案。 Anshuman Jaiswal 的回答是快速而直接的。如果您只是想让事情顺利进行,请参阅 Anshuman Jaiswal 的回答。
    猜你喜欢
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2010-09-22
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多