Search code examples
angularproperty-binding

Property Binding as function parameter in Html template of Angular 7


I have an issue in html template. I want to call a function and pass a param to function. This param is a property in component class. How could I bind this property in function call. I have tried different options but could not get success.

1.

<input type="button" class='Button' value='Back' 
(click)="showGrid('{{"./app/setup/" + url}}')" />

2.

<input type="button" class='Button' value='Back' 
(click)="showGrid('./app/setup/ + {{url}}')" />
  1. Using Getter in component.

    get myUrl = function(){ return "./app/setup/" + ${this.Url} }

In html,

<input type="button" class='Button' value='Back' 
(click)="showGrid('{{myUrl}}')" />

How could I bind the property in function call. Please suggest.

Thanks,


Solution

  • Its always a good idea to have these literals as const. Never hardcode these values in view (html).

    Use below approach.

    app.component.ts

    import {Component} from '@angular/core';
    
    @Component({
        selector: 'app',
        templateUrl: 'app.component.html'
    })
    export class AppComponent {
    
        appUrls = APP_URLS;
    
        constructor() { }
    
        showGrid(url) {
            // to-do
        }
    }
    
    export const APP_URLS = {
        'BASEURL': '/something',
        'URL1': `./app/setup/${this.BASEURL}`,
    };
    

    app.component.html

    <input type="button" class='Button' value='Back' (click)="showGrid(appUrls.URL1)" />