Search code examples
htmlangulartypescripteditshow-hide

Hiding and Showing Edit Input not working(Angular)


I'm trying to make an Edit button, with an input field that appears/disappears when the button is pressed. It was working previously, however when I tried to make a Display form, it doesn't seem to recognize the "title.value" This is very strange. I'm using Boolean for an "edit" variable combined with a *ngIf to show/hide the form. If I take the *ngIf="edit" off, it works normally as a form that displays what you're written. Am I missing something?

Here's the HTML:

        <input type="text" #title *ngIf="edit"/>
        <button (click)="edit = !edit">Edit</button>
        <button (click)="getTitle(title.value)">Get Title</button>
        <h2>{{groupTitle}}</h2> 

and here's the .ts:

  public edit = false;
  public groupTitle = "";

  getTitle(val) {
    this.groupTitle = val;
  }

Solution

  • You have a problem with implementing together the ngIf directive and a reference to your input element as #title. In that case you can use hidden instead of ngIf.

    Here's your html:

    <input type="text" #title [hidden]="!edit"/>
    <button (click)="edit = !edit">Edit</button>
    <button (click)="getTitle(title.value)">Get Title</button>
    <h2>{{groupTitle}}</h2> 
    

    There are couple more elegant ways to bind a value and render it on a page.

    The first one is to get rid of the Get title button and use (input) method directly on an input element. In that case, Html looks like:

    <input type="text" #title *ngIf="edit" (input)="getTitle(title.value)"/>
    <button (click)="edit = !edit">Edit</button>
    <h2>{{groupTitle}}</h2>
    

    The second one is to use [(ngModel]) instead of the getTitle method and bind your input value directly to the groupTitle variable.

    Html will look like:

    <input type="text" #title *ngIf="edit" [(ngModel)]="groupTitle"/>
    <button (click)="edit = !edit">Edit</button>
    <h2>{{groupTitle}}</h2>
    

    Your .ts file:

    edit = false;
    groupTitle = "";