【问题标题】:In Angular 7, ViewChild is undefined when using in *ngIf在 Angular 7 中,ViewChild 在 *ngIf 中使用时未定义
【发布时间】:2019-05-07 03:38:45
【问题描述】:

在 *ngIf 指令中使用 ViewChild 时,我将 Button 设为未定义。但是当我检查日志时,它会显示如下内容

https://i.stack.imgur.com/mpb16.png

就我而言,它仍然无法正常工作。有人可以帮忙吗?

HTML 代码

<div *ngIf="someCondition()">
<div class="row top-container">
    <div class="col-md-6">
      <h1 class="text-center">Registered </h1>
    </div>

    <div class="col-md-6">
      <div class="pull-right header-buttons-container">
        <button #registerPartnerButton id="registerPartner" class="btn btn-primary" type="button"  (click)="registerUser()">Register</button>
      </div>
    </div>
  </div>
</div>

TS 代码

registerButton: ElementRef;
@ViewChildren('registerPartnerButton') set someDummyName(content: ElementRef) {
    this.registerPartnerButton = content;
  };
constructor(changeDetector: ChangeDetectorRef) {}

问题: 应用上述解决方案后,我将 registerPartnerButton 设置为未定义。但是当我检查日志时,它会显示如下内容

https://i.stack.imgur.com/mpb16.png

我希望 ViewChild 不能未定义。

【问题讨论】:

    标签: angular7 angular-ng-if viewchild


    【解决方案1】:
    Finally I fixed it by applying below solution:
    
    registerButton: ElementRef;
    @ViewChildren('registerPartnerButton') set setButton(content: QueryList<ElementRef>) 
      {
        if(content.length > 0) {
         this.registerButton = content.first;
         // do further actions
        }
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 2020-08-02
      • 2021-07-26
      • 2017-11-25
      • 2021-07-10
      • 2017-01-14
      相关资源
      最近更新 更多