如何在模板中显示数据

How to display the data in template

我是 Angular2 的新手。

sample.html

<label>Name:</label>
<input type="text" [(ngModel)]="yourName" placeholder="Enter a name here">


<button (click)="sendData(yourName)">send data</button>
<p>{{receivedData}}</p>

sample.ts

import {Component} from 'angular2/core';

@Component({
selector: 'hello-world',
templateUrl: 'src/hello_world.html'
})
export class HelloWorld {
yourName: string = '';
receviedData : string = "";
console.log(receivedData);
sendData(yourName) : void{
console.log("sent",yourName);
receivedData = yourName;

}

}

我正在尝试将数据作为输入发送到 sendata 函数,然后将其分配给 receivedData 变量,然后使用插值在模板中显示 receivedData 变量。

 I appreciate any help related to this.

 Thanks

你快到了。您需要更改您的组件 ts 文件。您正在使用以下内容:

receivedData = yourName;

但是,您需要使用以下内容:

this.receivedData = yourName;

第一个尝试将值赋给局部变量,但答案是将值赋给全局变量。

希望对您有所帮助。