2017-09-20 14 views
1

main.component.html角4傳遞數據的HTML

<form (submit)="onSubmit()"> 
    height: 
    <input type="number" name="height" [(ngModel)]="user.height"> 
    <br><br> 
    Weight: 
    <input type="number" name="weight"[(ngModel)]="user.weight"> 
    <br><br> 
    <input type="submit"> 
</form> 

<h5 *ngFor="let user of users"> 

    {{user.score}} 

</h5> 

main.component.ts

export class MainComponent implements OnInit { 
    users = []; 

    user = { 
     height: 0, 
     weight: 0, 
    }; 

    onSubmit() { 
     console.log(this.user.height); 
     console.log(this.user.weight); 

     var score = this.user.weight * this.user.height; 
     this.users.push(score); 

     console.log(score); 


     this.user = { 
      height: 0, 
      weight: 0 
     } 
    } 
} 

this.user.weight和this.user.height相乘,並保存在VAR得分了。但是,如何將var分數傳遞到我的main.component.html中?我試圖推動用戶數組中的分數,但它沒有出現在我的main.component.html中。

+0

您在'user'中沒有成員'score'。添加它並將計算值存儲到它。 –

+0

你正在使用TypeScript,但你不能在任何地方使用類型。指定變量的類型,編譯器會告訴你你做錯了什麼。 '用戶'應該是(我猜)是一個用戶數組(Array''),但是你將分數推到這個數組(類型號)。您應該顯示每個用戶的分數,但是您沒有任何用戶分數。此外,您的代碼不縮進,使其非常難以閱讀。這是所有基本的東西。學習並應用基礎知識。 –

回答

1

不要將其推入用戶;刪除var並使用this.score = this.user.weight * this.user.height,然後在您的main ... html中,您可以使用爲{{score}}

1

得分不是目標,它應該是

<div *ngFor="let user of users"> 
<h1>{{user }}</h1> 
</div> 
+0

'用戶'是一個對象。 'users'是一個數組。不要錯過#' –

+1

@ i - no:閱讀代碼:它使用'var score = this.user.weight * this.user.height填充數組。 this.users.push(分數);'。所以數組的elemtns是數字。 –

+1

@ i--實際得分 – Sajeetharan

0

試試這個:

<h5 *ngFor="let user of users"> 
{{user | json}} 
</h5> 
+0

請添加解碼代碼。請閱讀[回答] –