我是Angular的新手,我正在努力创建一个简单的脚本,以便在表单输入的值发生变化时更新价格。似乎有几种不同的方法可以将Angular与类驱动和指令驱动的模型一起使用。阅读主角网站上的文档,但没有运气。
import { Component } from '@angular/core';
export class Ticket {
ticketNumber: number;
name: string;
price: number;
}
@Component({
selector: 'my-app',
template: `
<form name="myForm">
<div class="ticket box_shadows">
<div class="ticket_title">{{ticket.name}}</div>
<input type="number" name="myInput" class="ticket_ammount" min="1" max="10" value="{{ticket.ticketNumber}}"required ng-class="updatePrice(price,ticketNumber)">
<div class="ticket_details"><input class="ticket_details_input" type="text" placeholder="Name:" required></div>
<div class="ticket_details"><input class="ticket_details_input" type="email" placeholder="your@email.com" required></div>
<div class="ticket_details"><input class="ticket_details_input" type="text" placeholder="+852" required></div>
<div class="ticket_price">$ <input type="number" name="price" value="{{ticket.price}}|>
<button type="button" class="ticket_button">Book</button>
</div>
</div>
</form>
`
})
//creates the class
export class AppComponent {
ticket: Ticket = {
ticketNumber: 1,
name: 'Ticket',
price: 300
};
//updates the price on a new click
updatePrice(value, ticketN){
value = value * ticketN;
return value;
// this then needs to be passed back to the price input field.
}
}
-----更新------- 所以我遇到了调用两个类的问题,并尝试让它们进行交互。我对代码进行了条纹化并重新开始,这就是我所做的工作。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<form>
<div class="ticket box_shadows">
<div class="ticket_top">
<div class="ticket_title">{{title}}</div>
<input type="number" name="myInput" class="ticket_ammount" min="1" max="10" [(ngModel)]="ticket" (click)="updatePrice()" required>
</div>
<div class="ticket_btm">
<div class="ticket_price"><span>$</span><input type="number" [(ngModel)]="totalPrice" class="ticket_price_number" disabled></div>
<div class="ticket_btm_spacer"></div>
<button type="button" class="ticket_button">Book</button>
</div>
</div>
</form>
`
})
export class AppComponent {
ticket: number = 1;
title: string = "Ticket";
price: number = 300;
totalPrice: number = 300;
updatePrice(){
this.totalPrice = this.price * this.ticket;
if(this.ticket >= 2){
this.title = "Tickets";
}
else{ this.title = "Ticket";}
}
}
答案 0 :(得分:2)
要以双向绑定值输入,您需要用户ngModel
。
<input [(ngModel)]="ticket.price">