ElementRef 未定义

Gib*_*hah 3 focus angular-ng-if angular elementref

我正在使用 angular 6 应用程序。我有一个 textarea,我想在页面加载后立即关注它。我不能这样做。

这是页面的样子:

<div fxLayoutAlign="begin">
  <button mat-button color="primary" [routerLink]="['/Administration']">
    <i class="far fa-arrow-alt-circle-left"></i> Back to Administration
  </button>
</div>
    <div class="app-loading" *ngIf="_loading">
      <mat-spinner diameter=100></mat-spinner>
    </div>
    <div *ngIf="!_loading">

    <div class="knowledgeBody">

      <div *ngIf="_mode === 'view'">
        {{ _knowledgeText }}
        <div fxLayoutAlign="end">
          <button mat-button (click)="edit_clicked()" disabled="{{ _knowledgeText.trim().length === 0 }}">
            <i class="fas fa-edit"></i> Edit
          </button>
        </div>
      </div>

      <div *ngIf="_mode !== 'view'">
        <textarea matInput [(ngModel)]="_knowledgeText" cdkTextareaAutosize #knowledgeTextarea>
          {{ _knowledgeText }}
        </textarea>

        <div fxLayoutAlign="end">
          <button mat-button (click)="save_clicked()" disabled="{{ _knowledgeText.trim().length === 0 }}">
            <i class="fas fa-save"></i> Save
          </button>
        </div>
      </div>

  </div>

</div>
Run Code Online (Sandbox Code Playgroud)

感兴趣的文本区域是#knowledgeTextarea。

这是页面的组件:

@Component({
  selector: 'app-knowledge',
  templateUrl: './knowledge.component.html',
  styleUrls: ['./knowledge.component.scss']
})
export class KnowledgeComponent implements OnInit {

  private _mode : string;
  private _loading : boolean;
  private _knowledgeId : string;
  private _knowledgeText : string;
  private _description : string;
  private _groupPK : string;

  @ViewChild('knowledgeTextarea') knowledgeTextarea : ElementRef;

  constructor(private _activatedRoute : ActivatedRoute,
    private _watermelonService : WatermelonService,
    private _logService : LoggingService,
    private _dialog: MatDialog) {
      this._loading = true;
    }

  ngOnInit() {
…
    this.knowledgeTextarea.nativeElement.focus();
…
  }
…
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到以下错误:

Cannot read property ‘nativeElement’ of undefined.
Run Code Online (Sandbox Code Playgroud)

我已经读过,当您在 *ngIf 块中使用 # 标识 (#knowledgeTextarea) 引用页面上的元素时,可能会发生这种情况。所以这…

  <div *ngIf="_mode !== 'view'">
    <textarea matInput [(ngModel)]="_knowledgeText" cdkTextareaAutosize #knowledgeTextarea>
      {{ _knowledgeText }}
    </textarea>
</div>
Run Code Online (Sandbox Code Playgroud)

…不管用。

但是,还有什么选择呢?

我试过这个…

  <div *ngIf="_mode !== 'view'">
    <textarea matInput [(ngModel)]="_knowledgeText" cdkTextareaAutosize #knowledgeTextarea>
      {{ _knowledgeText }}
    </textarea>
    {{ knowledgeTextarea.focus() }}
</div>
Run Code Online (Sandbox Code Playgroud)

......这奏效了,但后来我得到了一个 ExpressionChangedAfterItHasBeenCheckedError,JB Nizet 告诉我不要在这里做:获取 ExpressionChangedAfterItHasBeenCheckedError 错误

如果有其他方法可以做到这一点,请告诉我。我想要的只是在页面加载时能够给 textarea 焦点。任何实现这一点的方式都将不胜感激。谢谢。

Sun*_*ngh 12

问题是在呈现之前访问元素。您必须确保在使用内容之前呈现内容。因此ngOnInit,不要在内部访问它,而应该在ngAfterViewInit.

 @ViewChild('knowledgeTextarea') knowledgeTextarea: ElementRef;

  ngAfterViewInit() {
    this.knowledgeTextarea.nativeElement.focus();
  }
Run Code Online (Sandbox Code Playgroud)

工作示例在这里 - https://stackblitz.com/edit/angular-jjyfwf