Ciprian
Ciprian

Reputation: 3226

Angular 2 add attribute to element conditionally

I have two buttons, going and maybe:

  toggles: any[] = [
    { response: 'going' },
    { response: 'maybe' }
  ];

which I display like this:

          <ion-col col-12 style="min-height: 250px;">
                <img class="event-home-img" src="{{mainEventImage}}" />
            </ion-col>

            <ion-col *ngFor="let toggle of toggles" col-6 style="text-align: center;">
                <button (click)="response(toggle.response)" ion-button color="danger" [attr.outline]="guestResponse !== toggle.response ? true : null"
                    full>
                    {{toggle.response}}
                </button>
            </ion-col>

guestResponse returns going or maybe based on the user's response. What I need is to add outline to the element if guestResponse doesn't match toggle.response. Now it doesn't add outline to either element.

Edit *** Response function

public guestResponse: string;

ngOnInit() {
const responses = ['going', 'maybe'];

    for (const key in responses) {
      if (responses.hasOwnProperty(key)) {
        this.db.object(`/events/${this.id}/${responses[key]}/${this.uid}`).valueChanges()
          .takeUntil(this.ngUnsubscribe)
          .subscribe((response) => this.getCurrentResponse(response, responses[key]));
      }
    }
}

  getCurrentResponse(response, key) {
    if (response) {
      this.guestResponse = key;
    }
  }

  response(event: string) {
    console.log(event);
    if (this.uid) {
      this.db.object(`/users/${this.uid}`).valueChanges()
        .takeUntil(this.ngUnsubscribe)
        .subscribe(user => this.setResponse(user, event));
    }
  }

Upvotes: 0

Views: 255

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58593

Please add :

this.guestResponse = event; inside your response(event: string) { ... } function.


response(event: string) {
    console.log(event);

    // add here if you want to show directly on click 
    // this.guestResponse = event; 

    if (this.uid) {
      this.db.object(`/users/${this.uid}`).valueChanges()
        .takeUntil(this.ngUnsubscribe)
        .subscribe(user => { 
            this.setResponse(user, event)
            // add here if you want after some db operation 
            // this.guestResponse = event;  
        });
    }
}

Upvotes: 1

Related Questions