英文:
@ViewChild is undefined in afterViewInit using FormControl
问题
我有一个带有FormControl的nbInput:
https://akveo.github.io/nebular/docs/components/input/overview#nbinputdirective
我想在控制器中使用@ViewChild来访问它,但它返回undefined。以下是我的代码:
<section>
  <nb-form-field>
    <nb-icon nbPrefix [icon]="vm.icon"></nb-icon>
    <input
      #inputField
      class="input"
      type="text"
      nbInput
      [formControl]="input"
      placeholder="{{ vm.placeholder }}"
      (blur)="onBlur()"
      [nbDatepicker]="datePicker"
    ></input>
    <nb-rangepicker #datePicker></nb-rangepicker>
  </nb-form-field>
</section>
@ViewChild('inputField') inputField: ElementRef;
ngAfterViewInit(): void {
  console.log(this.inputField); //返回undefined
}
请注意,我已将HTML和TypeScript代码分别标注出来,以便您更容易理解。
英文:
I have an nbInput with FormControl:
https://akveo.github.io/nebular/docs/components/input/overview#nbinputdirective
I want to access this in controller using @ViewChild but it returns undefined. Following is my code:
<section>
 <nb-form-field>
    <nb-icon nbPrefix [icon]="vm.icon"></nb-icon>
    <input
      #inputField
      class="input"
      type="text"
      nbInput
      [formControl]="input"
      placeholder="{{ vm.placeholder }}"
      (blur)="onBlur()"
      [nbDatepicker]="datePicker"
    />
    <nb-rangepicker #datePicker></nb-rangepicker>
  </nb-form-field>
</section>
@ViewChild('inputField') inputField: ElementRef;
  ngAfterViewInit(): void {
    console.log(this.inputField); //returns undefined
  }
答案1
得分: 1
自从您使用了 rxLet,afterViewInit 阶段不会可用视图子组件。
您有两种选择:
- 在 
inputField上使用 setter,这样您将在子组件设置后收到调用。 - 使用 
ViewChildren并使用ViewChildren.changes来获取通知,以便在项目数发生更改时(在您的情况下从 0 到 1 个子组件)时获得通知。 
英文:
Since you use rxLet the viewchild won't be available at afterViewInit.
You have 2 possibilites :
- use a setter on 
inputFieldso you will get a call once the child is set. - Use 
ViewChildrenand useViewChildren.changesto get a notification when there is a change on number of items (in your case from 0 to 1 child). 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论