1

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.