Mauricio Gracia Gutierrez
Mauricio Gracia Gutierrez

Reputation: 10844

How to Focus a TextArea that has an ngif

I have the following Angular 2 component and I need the textarea with id bannernote to be focused as as soon as it becomes visible (isEditEnabled)

<div class="cont-notesbanner">
  <p class="triangle"></p>
  <h3 class="tit-notesbanner">Add notes:</h3>

  <form (ngSubmit)="onSubmit(f)" #f="ngForm">
    <p
      class="p-notesbanner"
      *ngIf="!isEditEnabled"
      [ngClass]="currentAsset.notes.length === 0 ? 'it-place' : ''"
    >
      {{ currentAsset.notes.length === 0 ? "Add notes" : currentAsset.notes }}
    </p>
    <textarea 
      rows="4"
      cols="50"
      *ngIf="isEditEnabled"
      class="txt-notesbanner"
      name="bannernote"
      id="bannernote"
      rows="10"
      [(ngModel)]="currentAsset.notes"
      #bannernote
      onload="$('#bannernote').focus();"
    ></textarea>

    <div class="txt-right">
      <a class="smallButton" (click)="onCloseBannernotes()">Cancel</a>
      <a
        class="smallButton"
        (click)="onEditBannernotes()"
        *ngIf="!isEditEnabled"
        >Edit</a
      >
      <button type="submit" class="smallButton" *ngIf="isEditEnabled">
        Accept
      </button>
    </div>
  </form>
</div>

I have tried to achieve that using the "onshow" and "onload" events as you can see above without success

I have also adde code inside this method that is called whenever the the button is toggled from "Edit" to "Accept" like document.getElementById("bannernotes").focus But this does not work since when is being called that element has not been render because of the ngif has not been "executed"

onEditBannernotes() {
  this.isEditEnabled = !this.isEditEnabled;
}

Upvotes: 2

Views: 4545

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73721

You can access the element in code with @ViewChild. Since the element may not be available initially, define the associated property as a setter, and set the focus in it. As suggested by @Stefan in a comment, check first if the element reference is defined; it becomes undefined when the element is removed from the view.

// Set the focus on the textarea as soon as it is available
@ViewChild("bannernote") set bannerNoteRef(ref: ElementRef) {
  if (!!ref) {
    ref.nativeElement.focus() ;
  }
}

See this stackblitz for a demo.

Upvotes: 5

JoH
JoH

Reputation: 554

Use the @ViewChild() decorator to retrieve your textearea element. Put an identifier on your textarea like this: <textarea #myTextarea></textarea>

Don't forget to implements AfterViewInit interface.

 @ViewChild('myTextarea') textArea;

 ngAfterViewInit() {            
    this.textArea.focus();
 }

Upvotes: 1

Related Questions