Search code examples
angularangular-materialtooltip

Angular make dynamic tooltip message


  • I want to make one tooltip component for If my application running on Development mode than tooltip will show in my project but in Production mode this will not display.

  • In tooltip I want to show calculation on particular field like I have one control which calculate Control A and Control B value so When I go to this control tooltip than I want to show "Control A + Control B" So in my application I will identify all control calculations. I am using Angular 16 please suggest me way.

calcualtion.ts

    export class Calculations {
    static calculateNetAmount(form: FormGroup) {
        let retVal: number = form.controls['totalAmount'].value - form.controls['totalTaxAmount'].value
        form.controls['netAmount'].setValue(retVal);
    }
}

html:

<input type="number" formControlName="netAmount">
  • Here I want to show one tooltip above the input tag and this tooltip contains string message like "NetAmount = TotalAmount - TotalTaxAmount"

  • I have 100 plus static Function in my Calculations class so I want each and every control identify with specific message so please suggest me way to display this messages dynamically.


Solution

  • You can achieve by below ways:

    export class Calculations {
        public setFormulaTooltip(form:FormGroup,fieldName:string,information:string){
            const control = form.get(fieldName) as FormControl; 
            //@ts-ignore       
            control['tooltip'] = information ;
        }
        static calculateNetAmount(form: FormGroup) {
            let retVal: number = form.controls['totalAmount'].value - form.controls['totalTaxAmount'].value;
            this.setFormulaTooltip(form,'netAmount','totalAmount - totalTaxAmount');
            form.controls['netAmount'].setValue(retVal);
        }
    } 
    

    Write function for calculate values & set message for control.

    Html FOR COMMON COMPONENT

    <img src="../../../../../assets/images/svg/Fields/Areyousure-blue.svg" class="formula" 
         matTooltip="{{this.tooltipMessage}}" *ngIf="this.tooltipMessage" />
    <input type="number" formControlName="netAmount">
    

    Need to give imge for display tooltip message when message string available.

    .ts File FOR COMMON COMPONENT

    this.parentFormGroup.controls[this.formDisplayFieldName].valueChanges.subscribe((data: any) => {
        //@ts-ignore
        if(this.parentFormGroup!.get(this.formDisplayFieldName)['tooltip']){
            //@ts-ignore
            this.tooltipMessage = this.parentFormGroup!.get(this.formDisplayFieldName)['tooltip']
        }
    });
    

    when your form value change then need to set tooltip message.