Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 bind using conditional operator

I have a question about the binding in angular2.

I wrote a simple component, this is the code:

@Component({
    selector: 'drawer-item',
    templateUrl: '../res/views/drawer-item.html'
})
export class DrawerItemComponent
{
    @Input() text:string;
    @Input() icon:string;
    @Input() textClass:string;
}

<div class="drawer-item-text word-wrap {{textClass}}"> {{text}}</div>
<i class="mdi mdi-{{icon}} drawer-item-img"></i>

I use it like this:

<drawer-item (click)="selectCompany()" [text]="selectedCompanyLabel" [icon]="selectedCompanyIcon" [textClass]="selectedCompanyClass"></drawer-item>

As you can see I'm binding the text with variable, for example with selectedCompanyLabel. In this way everything works great, and if selectedCompanyLabel change tha label changes as well.

I would avoid that variable using something like:

[text]="company ? 'company.name' : 'Select a company'"

But is this way the content is not binded. So if company changes, the label is not updated.

But if I use that strategy in a style, it works! For example something like works great:

<div class="company ? 'italic' : 'bold'"> ... </div>

Do you know why?

Thanks a lot

like image 585
user3471528 Avatar asked Apr 11 '16 13:04

user3471528


People also ask

How use ternary operator in Angular TS file?

The Typescript conditional operator is a Ternary Operator, which takes three operands. The first operand is a condition to evaluate. It is followed by a question mark ( ? ), then an expression ( expression1 ). It is then followed by a colon ( : ) and second expression ( expression2 ).

How do you categorize data binding types?

As mentioned earlier, one-way data binding in Angular can be of three types i.e Interpolation, Property binding, and Event binding.

What is data binding in Angular with example?

Two-way data binding is a two-way interaction, data flows in both ways (from component to views and views to component). Simple example is ngModel. If you do any changes in your property (or model) then, it reflects in your view and vice versa. It is the combination of property and event binding.

What is data binding in Angular and explain types of binding?

Angular data binding is a two-way process: it can both send and receive data. This means that when you change something in your view, the model updates automatically, and vice versa. The ngModel directive makes this two-way data binding possible.


2 Answers

I would use the following instead:

[text]="company ? company.name : 'Select a company'"

No quotes for company.name.

like image 110
Thierry Templier Avatar answered Oct 19 '22 20:10

Thierry Templier


Not sure from your question what the problem is but I guess this is what you're looking for

[text]="company?.name"
like image 32
Günter Zöchbauer Avatar answered Oct 19 '22 22:10

Günter Zöchbauer