Arun Selva Kumar
Arun Selva Kumar

Reputation: 2732

How to Bind two properties in Angular

I am trying to experiment with angular bindings, I am stuck with a weird situation.. I need to bind two properties - here 'code' and 'title' are the binding properties

<app-title-component fxFlexFill [title]="code + title"></app-title-component>

This works fine! I get the value of concated code and title value in the screen.

Now I wanted to have a static text between the two bindable properties Say, I want the result to be

CodeValue - CodeTitle Value

How to do that? Is there a way to do binding using string interpolation?

Upvotes: 2

Views: 1350

Answers (2)

dev-dan
dev-dan

Reputation: 6283

here are two ways you can get this required result. Starting with a very simple method mentioned within the comments.

<app-title-component fxFlexFill [title]="code + ' - ' + title"></app-title-component>

secondly you can use string interpolation looking like so. Be sure to be using back ticks ( ` ) for this interpolation, else it will be ignored.

<app-title-component fxFlexFill [title]="result"></app-title-component>

within your template

public get result(): string
{
    return `${this.code} - ${this.title}`;  
} 

Here is an article looking at How Angular can deal with string interpolation.

Upvotes: 3

Jota.Toledo
Jota.Toledo

Reputation: 28434

You could simply define a getter in your component as follows:

class FooComponent {
  title:string;
  code:string;
  get formatedTitle(){return `${this.code} - ${this.title}`;}
}

<app-title-component fxFlexFill [title]="formatedTitle"></app-title-component>

Upvotes: 2

Related Questions