Finish the app
ChatAreaHeaderComponent
is quite simple. It only shows the selected channel name.
src/app/chat/components/chat-area-header.component.ts
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'my-chat-area-header',
changeDetection: ChangeDetectionStrategy.OnPush,
styles: [`
.wrapper {
padding: 0 .5rem;
}
`],
template: `
<div class="wrapper">
<h3># {{channelName}}</h3>
</div>
`
})
export class ChatAreaHeaderComponent {
@Input() channelName: string;
}
src/app/chat/components/channel-add.component.ts
import { Component, OnInit, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'my-channel-add',
changeDetection: ChangeDetectionStrategy.OnPush,
styles: [`
.wrapper {
margin: .5rem;
}
`],
template: `
<div class="wrapper">
<form [formGroup]="channelForm" (ngSubmit)="onAddChannel()">
<input formControlName="name" placeholder="add channel" />
</form>
</div>
`
})
export class ChannelAddComponent implements OnInit {
@Output() addChannel = new EventEmitter<string>();
channelForm: FormGroup;
constructor(
private fb: FormBuilder
) {}
ngOnInit() {
this.channelForm = this.fb.group({
name: ['', Validators.required]
});
}
private onAddChannel() {
if (!this.channelForm.valid) return;
this.addChannel.emit(this.channelForm.value.name);
this.channelForm.reset();
}
}
src/app/chat/components/chat.component.ts
// ...
template: `
<!-- ... -->
<my-channel-add
(addChannel)="onAddChannel($event)">
</my-channel-add>
<!-- ... -->
<my-chat-area-header
[channelName]="chatService.channel?.name">
</my-chat-area-header>
<!-- ... -->
`,
})
export class ChatComponent implements OnInit, OnDestroy {
// ...
onAddChannel(channelName: string) {
this.chatService.addChannel(channelName);
}
}
src/app/chat/services/chat.service.ts
// ...
addChannel(channelName: string): void {
const channel: Channel = {
_id: String(this.channelsDb.length),
name: channelName
};
// fake API, add channel to the database
this.channelsDb = [...this.channelsDb, channel];
this.channels = [...this.channels, channel];
}
src/app/app.module.ts
// ...
import { ChannelAddComponent } from './chat/components/channel-add.component';
import { ChatAreaHeaderComponent } from './chat/components/chat-area-header.component';
@NgModule({
// ...
declarations: [
// ...
ChannelAddComponent,
ChatAreaHeaderComponent
],
// ...
Now your app should look like this:
Run the live example for this part.