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
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 ).
As mentioned earlier, one-way data binding in Angular can be of three types i.e Interpolation, Property binding, and Event binding.
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.
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.
I would use the following instead:
[text]="company ? company.name : 'Select a company'"
No quotes for company.name
.
Not sure from your question what the problem is but I guess this is what you're looking for
[text]="company?.name"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With