Skip to content

Commit 45e4287

Browse files
committed
feat: introduce reactive form
1 parent b95ee7d commit 45e4287

File tree

3 files changed

+24
-7
lines changed

3 files changed

+24
-7
lines changed

src/app/app.module.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@ import { AppRoutingModule } from './app-routing.module';
55
import { AppComponent } from './app.component';
66
import { TemplateDrivenComponent } from './template-driven/template-driven.component';
77
import { ReactiveComponent } from './reactive/reactive.component';
8+
import { ReactiveFormsModule } from '@angular/forms';
89

910
@NgModule({
1011
declarations: [AppComponent, TemplateDrivenComponent, ReactiveComponent],
11-
imports: [BrowserModule, AppRoutingModule],
12+
imports: [BrowserModule, AppRoutingModule, ReactiveFormsModule],
1213
providers: [],
1314
bootstrap: [AppComponent],
1415
})

src/app/reactive/reactive.component.html

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@
44
<p>REACTIVE</p>
55
</div>
66
<h1>Welcome</h1>
7-
8-
<form class="form">
9-
<input type="text" placeholder="Username" />
10-
<input type="password" placeholder="Password" />
11-
<button type="submit" id="login-button">Login</button>
7+
<form class="form" [formGroup]="loginForm" (ngSubmit)="submit()">
8+
<input type="text" placeholder="userName" formControlName="userName" />
9+
<input type="password" placeholder="Password" formControlName="password" />
10+
<button type="submit" id="login-button" [disabled]="!loginForm.valid">Login</button>
1211
</form>
1312
</div>
1413

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,29 @@
11
import { Component, OnInit } from '@angular/core';
2+
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
23

34
@Component({
45
selector: 'app-reactive',
56
templateUrl: './reactive.component.html',
67
styleUrls: ['./reactive.component.css'],
78
})
89
export class ReactiveComponent implements OnInit {
9-
constructor() {}
10+
constructor(private builder: FormBuilder) {}
11+
12+
loginForm = this.builder.group({
13+
userName: [''],
14+
password: [''],
15+
});
16+
17+
// this also possible though it could be troublesome (using instance)
18+
/* protected loginForm = new FormGroup({
19+
userName: new FormControl(''),
20+
password: new FormControl(''),
21+
});*/
1022

1123
ngOnInit(): void {}
24+
25+
submit() {
26+
console.log('submit');
27+
console.log(this.loginForm.value);
28+
}
1229
}

0 commit comments

Comments
 (0)