Búsqueda de sitios web

¿Cómo enlazar una expresión de Angular 2 y un método de TypeScript?


Lo que estoy tratando de hacer es mostrar el nombre completo, cuando se ingresan el nombre y el apellido.

Esto funciona:

<h1 [hidden]="!firstName || !lastName">Hello {{lastName + ', ' + firstName}}!</h1>

Esto no funciona (¿cuál es la manera correcta de invocar un método definido en la clase?):

<!--h1 [hidden]="!firstName || !lastName">Hello {{fullName()}}!</h1!-->

Esto tampoco funciona:

<button ng-click="alertFullName()">show full name</button>

Aquí están los archivos: index.html:

<!DOCTYPE html>
<html>

  <head>
    <title>Angular 2 QuickStart</title>

    <!-- 1. Load libraries -->
    <script src="https://rawgithub.com/systemjs/systemjs/0.19.6/dist/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/angular2.dev.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        transpiler: 'typescript', 
        typescriptOptions: { emitDecoratorMetadata: true }, 
        packages: {'src': {defaultExtension: 'ts'}} 
      });
    </script>

    <!-- 3. Bootstrap -->
    <script>
      System.import('angular2/platform/browser').then(function(ng){
        System.import('src/hello_world').then(function(src) {
          ng.bootstrap(src.HelloWorld);
        });
      });
    </script>

  </head>

  <!-- 4. Display the application -->
  <body>
    <hello-world>Loading...</hello-world>
  </body>

</html>

src/hello_world.html:

<label>Name:</label>
<input type="text" [(ngModel)]="firstName" placeholder="Enter first name here">
<input type="text" [(ngModel)]="lastName" placeholder="Enter last name here">
<hr>
<h1 [hidden]="!firstName || !lastName">Hello {{lastName + ', ' + firstName}}!</h1>
<!--h1 [hidden]="!firstName || !lastName">Hello {{fullName()}}!</h1!-->
<button ng-click="alertFullName()">show full name</button>

src/hola_mundo.ts:

import {Component} from 'angular2/core';

@Component({
  // Declare the tag name in index.html to where the component attaches
  selector: 'hello-world',

  // Location of the template for this component
  templateUrl: 'src/hello_world.html'
})
export class HelloWorld {
  firstName: string = '';
  lastName: string = '';
  function fullName(): string {
    return firstName + ', ' + lastName;
  }
  function alertFullName() {
    alert(firstName + ', ' + lastName);
  }
}

Respuesta #1

Además de lo que escribió @Günter Zöchbauer (es decir, use (click), no ng-click), este código

function fullName(): string {
   return firstName + ', ' + lastName;
}
function alertFullName() {
  alert(firstName + ', ' + lastName);
}

debería ser

fullName():string {
    return this.firstName + ', ' + this.lastName;
}
alertFullName() {
   alert(this.firstName + ', ' + this.lastName);
}

Respuesta #2

Si echamos un vistazo a la documentación de las plantillas de Angular 2, podemos ver que la interpolación en la forma de {{bindMe}} solo puede enlazarse a propiedades:

Las expresiones pueden usarse únicamente para enlazar a propiedades. Las expresiones representan cómo se deben proyectar los datos a la Vista. Las expresiones no deben tener ningún efecto secundario y deben ser idempotentes.

Esto significa que el siguiente ejemplo es 'ilegal' ya que representa una invocación de función:

<h1 [hidden]="!firstName || !lastName">Hello {{fullName()}}!</h1>

En su lugar, podrías tener un getter fullName que produzca el valor que deseas:

export class HelloWorld {
  firstName: string = '';
  lastName: string = '';
  get fullName () {
      return firstName + ' ' + lastName;
  }
}

Y luego usa fullName en tu plantilla:

<h1 [hidden]="!fullName.length">Hello {{fullName}}!</h1>

Artículos relacionados