How to bind an Angular 2 expression and TypeScript method?
In addition to what @Günter Zöchbauer wrote (i.e., use (click)
, not ng-click
), this code
function fullName(): string {
return firstName + ', ' + lastName;
}
function alertFullName() {
alert(firstName + ', ' + lastName);
}
should be
fullName():string {
return this.firstName + ', ' + this.lastName;
}
alertFullName() {
alert(this.firstName + ', ' + this.lastName);
}
If we take a look at the documentation for Angular 2 templates we can see that interpolation in the form of {{bindMe}}
can bind only to properties:
Expressions can be used to bind to properties only. Expressions represent how data should be projected to the View. Expressions should not have any side effect and should be idempotent.
This means the following example is 'illegal' as it represents a function invocation:
<h1 [hidden]="!firstName || !lastName">Hello {{fullName()}}!</h1>
You could instead have a getter fullName
which produces the value you want:
export class HelloWorld {
firstName: string = '';
lastName: string = '';
get fullName () {
return firstName + ' ' + lastName;
}
}
And then consume fullName
in your template:
<h1 [hidden]="!fullName.length">Hello {{fullName}}!</h1>