Add Form

There are two kinds of forms:

  • Template driven forms
  • Model drive or Reactive forms

Reactive form is more powerful when you have complex form. And we will use reactive form.

Import ReactiveFormsModule

Before we use the form, we need add ReactiveFormsModule in

src/app/app.module.ts

// ...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
    ReactiveFormsModule,
    // ...
  ],
  // ...
})
export class AppModule {}

User FormBuilder

First import

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

on the top of src/app/chat/components/chat.component.ts.

Then add these in the template:

<form [formGroup]="messageForm" (ngSubmit)="onSendMessage()">
  <input formControlName="message" placeholder="Click enter to send"/>
</form>

At last, add these in the class:

messageForm: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit() {
  this.messageForm = this.fb.group({
    message: ''
  });
}

onSendMessage() {
  const message = {
    _id: String(this.messages.length),
    channelId: '0',
    userId: '0',
    userName: 'Jack',
    content: this.messageForm.value.message,
    timestamp: new Date()
  };

  this.messages.push(message);

  this.messageForm.reset();
}

We created an FormGroup by using this.fb.group. And it takes a Object of configuration which format is key: value. In our app, the key is message, and the initial value is an empty string ''.

In template, it needs to be corresponding. We added [formGroup]="messageForm" in the <form></form>. Also we added formControlName="message" which message is the key we just added in the configuration.

So now when we press enter button, (ngSubmit)="onSendMessage()" event will be triggered. To get the value of message, we can use this.messageForm.value.message.

At last, we can reset the form to clean the text we just entered.

Add validator

To avoid users send empty messages, we can user validator.

Angular 2 provides some commonly used validators, such as required and minLength. In this case, we can use required.

ngOnInit() {
  this.messageForm = this.fb.group({
    message: ['', Validators.required]
  });
}

To check the validity of the form, we can use this.messageForm.valid which will return a boolean value.

onSendMessage() {
  if (!this.messageForm.valid) return;
  // ...
}

Run the live example for this part.

results matching ""

    No results matching ""