Angular if condition within component attributes

37 Views Asked by At

Apologies if this has been asked before, I've searched but couldn't find a solution so thought I'll ask to good ol' people here for help. Okay so the issue is, I have the following code,

<footer-price
    *ngIf="showPriceWithSavings"
    title="{{ getTitle() }}"
    price="{{ getPrice(id, shouldShowPrice) }}"
    info="or pay {{
      getInfo(id, shouldShowPrice).price | currency : 'GBP' : 'symbol' : '1.2-2'
    }}"
    discount="You’ve saved <b>{{ getSavePrice(id, shouldShowPrice).savings | currency : 'GBP' : 'symbol' : '1.2-2' }}</b>"
    [calculated]="true">        
</footer-price>

Now as for Info attribute, I want to put a condition here to either show the text to pay ... or display NO text at all. Can I put a condition inside the info attribute or do I need to create a completely new component with *ngIf condition?!?

Hope my question makes sense and looking forward to some wonderful solutions

1

There are 1 best solutions below

0
Benny Halperin On

I answered a similar question here: https://stackoverflow.com/a/76951173/2005232. Using a directive. Below is the directive code copied from there. You can reuse it and change the attribute names accordingly.

A working example can be found here: https://stackblitz.com/edit/conditional-formcontrolname

import { Directive, Input, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appConditionalName]',
  standalone: true
})
export class ConditionalNameDirective {
  @Input() readonly appConditionalName: string = '';
  @Input('condition') readonly condition: boolean = false;

  constructor(
        private readonly viewContainerRef: ViewContainerRef
  ) { }

  ngAfterViewInit(): void {
    if (this.condition) {
      const el = this.viewContainerRef.element.nativeElement as HTMLInputElement;

      el.setAttribute('formControlName', this.appConditionalName);
    }
  }
}

And this is how it's called from a parent component:

<input appConditionalName="firstName" [condition]="condition" />