10

There are toggle two button (edit and submit), which button should work like toggle show/hide style on click

<button (click)="showEditBtn = false;" *ngIf="showEditBtn;"> Edit</button>
<button (click)="showEditBtn =  true;" *ngIf="!showEditBtn;">Submit</button> 

I need showEditBtn variable should be true in default without touching script file

Is it possible to assign a value to a variable in the template, like below example?

<div> {{  let showEditBtn = true  }}  </div>

stackblitz example

5
  • 1
    @Shubham That's not going to work, it will give an error. Commented May 22, 2019 at 9:20
  • 1
    @Shubham this won't work as {{ }} is only used to print the output Commented May 22, 2019 at 9:20
  • 1
    possible duplicate of stackoverflow.com/questions/48959117/… Commented May 22, 2019 at 9:24
  • Thank you all, it was checking whether possible or not Commented May 22, 2019 at 9:26
  • Figured out. Check my answer Commented May 22, 2019 at 9:35

5 Answers 5

6

Figured out. It is a bit of a hack. But works perfectly

<div *ngIf="true; let showEditBtn">
    <div> {{ showEditBtn }} </div>
    <button (click)="showEditBtn = false" *ngIf="showEditBtn"> Edit</button>
    <button (click)="showEditBtn = true" *ngIf="!showEditBtn">Submit</button>
</div>
Sign up to request clarification or add additional context in comments.

Comments

4

You cannot create or set value in a variable inside interpolation {{ }}, interpolation is only used to print the output (value of variable).

Comments

3

Angular Interpolation is a way of data binding in Angular. And it will allow user to communicate between component and it's template (view).

String Interpolation is a one way data binding. In one-way data binding, the value of the Model is inserted into an HTML (DOM) element and there is no way to update the Model from the View.

Hope given link may help to understand well.

Comments

2

I highly recommend to not set or update variables in your template. All of your logic should be in the controller.

here is a simple example of how you can do it app.component.ts:

  public isEditMode: boolean;
  public toggleEditMode(): void {
      this.isEditMode = !this.isEditMode;
  }

app.component.html

<button (click)="toggleEditMode()" *ngIf="isEditMode;"> Edit</button>
<button (click)="toggleEditMode()" *ngIf="!isEditMode;">Submit</button>

Comments

0

There is no way in Angular2+ to initialize the variable value in the template. You must look into the ngOnInit() function.

1 Comment

Well, not officially but with a little hack you can.

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.