Angular 入门到精通 #06 - Using forms for user input

70 阅读1分钟

定义checkout form model

  1. 打开cart.component.ts

  2. 注入FormBuilder service到CartComponent

    constructor(
        private readonly cartService: CartService,
        private readonly formBuilder: FormBuilder
      ){}
    
  3. 使用FormBuilder group()方法来设置checkoutForm的属性,包括name和address

    checkoutForm = this.formBuilder.group({
        name: '',
        address: ''
      });
    
  4. 定义onSubmit方法,这个方法允许用户提交name和address。另外,调用CartService的clearCart方法来清空购物车

        this.items = this.cartService.clearCart();
        console.warn('Your order has been submitted', this.checkoutForm.value);
        this.checkoutForm.reset();
      }
    

创建checkout form

  1. 在cart.component.html的底部,添加一个HTML <form> 元素和一个Purchase按钮

  2. 使用formGroup属性来绑定checkoutForm和HTML<form>

    <form [formGroup]="checkoutForm">
    
        <button type="submit">Purchase</button>
    </form>
    

PS: 记得在app.module.ts中导入ReactiveFormsModule

```
imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ReactiveFormsModule
],
```

3. 绑定onSubmit方法到ngSubmit属性,为属性name和address添加输入框,并绑定formControlName属性,这个属性会绑定checkoutForm model到页面上的控件

```
<form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()" class="inputForm">
    <div>
        <label for="name">Name</label>
        <input id="name" type="text" formControlName="name">
    </div>

    <div>
        <label for="address">Address</label>
        <input id="address" type="text" formControlName="address">
    </div>

    <button type="submit">Purchase</button>
</form>
```

4. 最终的结果如下

Cart form submit