首页 > 解决方案 > Angular Forms,需要一些简单的例子

问题描述

我看到的很多官方教程似乎太健壮了。

我有一个带有“名称”和“密码”字符串的用户类。

我需要一个从这两个中获取用户输入并将其写入对象的表单。

然后将其发布到数据库中的表中。

我是 Angular 的新手,我没想到这么简单的形式会这么复杂。

标签: angularforms

解决方案


这是一个Stackblitz示例。

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports:      [ BrowserModule, ReactiveFormsModule, HttpClientModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { AuthService } from './auth.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent  {

  constructor(private authService: AuthService){}

  fg = new FormGroup({
    name: new FormControl(),
    password: new FormControl()
  })

  onSubmit(){
    this.authService.login(this.fg.value).subscribe();
  }
}

app.component.html

<form (ngSubmit)="onSubmit()" [formGroup]="fg">
    <div>
        <label for="username">Username</label>
        <input id="username" type="text" formControlName="name">
  </div>
  <div>
    <label for="password">Password</label>
    <input id="password" type="password" formControlName="password">
  </div>
  <button>Login</button>
</form>

auth.service.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Injectable({ providedIn: "root" })
export class AuthService {
  constructor(private httpClient: HttpClient) {}
  login(data: any) {
    return this.httpClient.post("your url", data);
  }
}

推荐阅读