简体   繁体   中英

How to display a hidden div on button click and hide the clicked button in Angular 2?

I'm facing difficulties in Angular UI development. Here I'm having a requirement that:

  • on click of Add Button it should show a hidden form:
  • on click of Add Button -> Add Button should hide
  • in hidden form there will be a button Cancel-
  • if I click on cancel the form should hide and add button should return

I have tried this using Angular 2 template syntax and by declaring nested boolean values, but I'm not getting the perfect answer.

How to do this in Angular 2 or 4? Do I have to use any host Listener or event emitter for this? I'm sharing my sample code and plunker:

template.html

<button(click)="addParameter=addParameter==true?false:true">
              Add</button>

            <div class="Parameters" *ngIf="addParameter==true">

            <input name="hello">

            <button (click)="hideForm();">Cancel</button>
            </div>

test.ts

export class App {

  private addParameter:boolean=false;

}

https://plnkr.co/edit/fa3Pdea1mB4RztAgOAW2?p=preview

You can do this in a couple of ways. Depending on if you want to handle it in component or in template. I personally prefer to keep template clean and do the "work" in component. So in that case your code would simply look like this:

<button *ngIf="!addParameter" (click)="toggleForm()">Add</button>
<div class="Parameters" *ngIf="addParameter">
  <input name="hello">
  <button (click)="toggleForm()">Cancel</button>
</div>

and TS:

toggleForm() {
  this.addParameter = !this.addParameter
}

DEMO: http://plnkr.co/edit/y3bDxsXMTYLtf8HI2PlA?p=preview


and as said, if you want to do this in template, it would look like this:

<button *ngIf="!addParameter" (click)="addParameter = !addParameter">Add</button>
<div class="Parameters" *ngIf="addParameter">
  <input name="hello">
  <button (click)="addParameter = !addParameter">Cancel</button>
</div>

DEMO: https://plnkr.co/edit/xcSzXGWOMNIhuZ83OXbs?p=preview

I think what you're looking for is something like:

<div>
      <form>
        <input name="hello">
        <button *ngIf="addingForm===false" (click)="addingForm = true">Add</button>
        <button *ngIf="addingForm===true" (click)="addingForm = false">Cancel</button>
      </form>
      <form *ngIf="addingForm===true">
        <input name="hidden">
      </form>
    </div>

In TS:

addingForm = false;

Like here: https://plnkr.co/edit/uXztfHwdWxuTVNIg6sxA?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM