我在这里有一个HTML代码(' signup.component.html')。它从用户收集数据。我想将这些数据动态添加到JSON数组中。
<div class="signup" *ngIf="!name; else forminfo">
<form [formGroup]="rForm" (ngSubmit)="addPost(rForm.value)" name="myForm">
<div class="form-container">
<div class="row columns">
<h1>Signup</h1>
<label>First Name
<input type="text" formControlName="fname">
</label>
<label>Last Name
<input type="text" formControlName="lname">
</label>
<label>E-Mail
<input type="text" formControlName="email" name="email">
</label>
<label>Password
<input type="password" formControlName="password1" name="password1">
</label>
<label>Confirm Password
<input type="password" formControlName="password2" name="password2">
</label>
<input type="submit" class="button expanded" value="Submit Form" [disabled]="!rForm.valid" (click)="validateEmail()" >
</div>
</div>
</form>
</div>
以下是我的打字稿(&#39; signup.component.ts&#39;)。我有&#39; fname&#39;,&#39; lname&#39;,&#39;电子邮件&#39;和密码1&#39;。 我想将这些数据存储到JSON数组中,以便我以后再访问它。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent {
rForm: FormGroup;
post:any; // A property for our submitted form
lname:string = '';
fname:string = '';
email:string = '';
password1:string = '';
password2:string = '';
constructor(private fb: FormBuilder) {
this.rForm = fb.group({
'fname' : [null, Validators.compose([Validators.required])],
'lname' : [null, Validators.compose([Validators.required])],
'email' :[null, Validators.compose([Validators.required, Validators.minLength(4)])],
'password1':[null, Validators.compose([Validators.required, Validators.minLength(4)])],
'password2':[null, Validators.compose([Validators.required, Validators.minLength(4)])]
});
}
addPost(post) {
this.fname = post.fname;
this.lname = post.lname;
this.email = post.email;
this.password1 = post.password1;
this.password2 = post.password2;
}
validateEmail(){
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
var password = document.forms["myForm"]["password1"].value;
var confirmPassword = document.forms["myForm"]["password2"].value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
return true;
}
}
答案 0 :(得分:0)
Angular的核心含义是双向数据绑定。
问:这是什么意思?答:简化 - &gt;你有.html和.ts文件。在html中你有输入(比如用户名),如果你开始在.ts方面输入用户名,那么对象或变量会自动更新。第二种方法是,如果您在.ts方面更改该变量或对象,则html也将更新。
所以在你的情况下输入:
<input type="text" formControlName="fname">
我想补充一下:
<input type="text" formControlName="fname" [(ngModel)]="firstName">
在.ts方面添加:
firstName: string;
答案 1 :(得分:0)
在html
<form [formGroup]="rForm" (ngSubmit)="addPost()" name="myForm">
在ts
addPost() {
console.log(this.rForm.value);
}