@ViewChild在使用FormControl后在afterViewInit中未定义。

huangapple go评论61阅读模式
英文:

@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:

&lt;section&gt;
 &lt;nb-form-field&gt;
    &lt;nb-icon nbPrefix [icon]=&quot;vm.icon&quot;&gt;&lt;/nb-icon&gt;
    &lt;input
      #inputField
      class=&quot;input&quot;
      type=&quot;text&quot;
      nbInput
      [formControl]=&quot;input&quot;
      placeholder=&quot;{{ vm.placeholder }}&quot;
      (blur)=&quot;onBlur()&quot;
      [nbDatepicker]=&quot;datePicker&quot;
    /&gt;
    &lt;nb-rangepicker #datePicker&gt;&lt;/nb-rangepicker&gt;
  &lt;/nb-form-field&gt;
&lt;/section&gt;

@ViewChild(&#39;inputField&#39;) inputField: ElementRef;
  ngAfterViewInit(): void {
    console.log(this.inputField); //returns undefined
  }

答案1

得分: 1

自从您使用了 rxLetafterViewInit 阶段不会可用视图子组件。

您有两种选择:

  • 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 inputField so you will get a call once the child is set.
  • Use ViewChildren and use ViewChildren.changes to get a notification when there is a change on number of items (in your case from 0 to 1 child).

huangapple
  • 本文由 发表于 2023年3月3日 20:06:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626856.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定