Harshit
Harshit

Reputation: 1565

How to define query parameters in [queryParams] directive in other ways in Angular 2?

I'm recently working on the issues related to queries. While working on a particular issue - I have need to define some query parameters. Here is the code snippet -

<a [routerLink]="resultsearch" [queryParams]="{query: result.label,
                                                       verify: false,
                                                       nav: 'filetype,protocol,hosts,authors,collections,namespace,topics,date',
                                                       start: 0,
                                                       indexof: 'off',
                                                       meanCount: '5',
                                                       resource: 'global',
                                                       prefermaskfilter: '',
                                                       rows: 10,
                                                       timezoneOffset: 0}"
          class="rellink">{{result.label}}</a>

The code here seems to be a lot messy in a HTML file. I wanted to know is there any way we can define them in .ts file of component and then pass the values in [queryParams] directive ? It would be great if someone can guide me in this. Thanks in advance! :)

Upvotes: 1

Views: 1414

Answers (1)

Joe Clay
Joe Clay

Reputation: 35857

The [...] syntax on an component property is called property binding - it sets the property to the value of whatever template expression you pass in.

At the minute, you're just passing a simple object directly as the expression, but that's not all you can do - the 'context' of the expression gives you access to all the member variables of your component class. It looks like you've already made use of this for your routerLink property and result! So, you can easily move the queryParams out into your component class and bind to it like so:

@Component({
  selector: 'my-component',
  template: `
    <a [routerLink]="resultsearch" [queryParams]="queryParams" class="rellink">
        {{result.label}}
    </a>
  `
})
export class MyComponent {
  resultsearch = "/whatever/your/path/is";    

  queryParams = {
    query: result.label,
    verify: false,
    nav: 'filetype,protocol,hosts,authors,collections,namespace,topics,date',
    start: 0,
    indexof: 'off',
    meanCount: '5',
    resource: 'global',
    prefermaskfilter: '',
    rows: 10,
    timezoneOffset: 0
  };

  result = {
      label: "hello, world"
  };
}

Upvotes: 2

Related Questions