Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

forms - Angular - use formControlName on object property

Here is what I have so far:

UserModel.ts

export class UserModel {
  id?: string = null;
  firstName = 'firstName';
  lastName = '';
  email = '';
  county = '';
  city = '';
  phone = '';
  password = '';
  role = '';
}

register.component.ts

export class RegisterComponent implements OnInit {
  registerForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.registerForm = this.formBuilder.group({
      user: new UserModel()
    });
  }

register.component.html

<form [formGroup]="registerForm">
  Value: {{registerForm.value.user | json}}
  <hr>
  <input type="text" formControlName="whatever I should put here">
</form>

What I want is to bind the input to let's say... user's first name, last name, email and so on. Is there any way to do that? Also, if I can, how do I add validators to user fields?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Before you bind formControlName in HTML you need to define then in you TS, like this:

ngOnInit(): void {
this.registerForm = this.formBuilder.group({
  id: ['', Validators.required],
  firstName: ['', Validators.required],
  email: ['', Validators.email],
  // Other fields
});

} To know more about the validators, check this Validating reactive froms for the HTML:

<form [formGroup]="registerForm"  (ngSubmit)="register()">
      <input type="text" placeholder="type your first name" formControlName="firstname">
      <input type="email" placeholder="you Email" formControlName="email">
      <!--Other fields-->
 </form>

Finally to get the form values:

register() {
console.log(this.registerForm.value);
if(this.loginForm.invalid){
  return;
}
// Create a User instance with the form value ...

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...