angular - Angular Forms,需要一些简单的例子
问题描述
我看到的很多官方教程似乎太健壮了。
我有一个带有“名称”和“密码”字符串的用户类。
我需要一个从这两个中获取用户输入并将其写入对象的表单。
然后将其发布到数据库中的表中。
我是 Angular 的新手,我没想到这么简单的形式会这么复杂。
解决方案
这是一个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);
}
}
推荐阅读
- javascript - React - 意外的模板字符串表达式:no-template-curly-in-string
- c++ - 使用 opencv 和 cpp 的应用程序的 Yocto 配方
- wordpress - Elementor:使用插件从构建器获取内容
- azure-rest-api - 获取 Azure VM AD 域
- java - 当玩家 1 的生命达到 0 时程序不会结束
- r - 更新闪亮中相同单选按钮的选择参数
- r - 如何在 R 中使用 Plotly 翻转 x 轴(180 度)
- python - 使用 json 文件输入附加列堆栈
- c# - 从串行端口处理程序调用函数花费了太多时间和处理器能力
- google-apps-script - 导入 CSV 时的问号符号