Generating the Tweets Add page

To generate the Tweets Add page, we use the following code:

ng g c tweets-add

This will generate the tweets-add.component.css, tweets-add.component.html, tweets-add.component.spec.ts, and tweets-add.component.ts files under the /src/app/tweets-add directory.

tweets-add.component.ts will look like the following after modifying the stub code:

import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ActivatedRoute, Router } from '@angular/router';
import { TweetsService } from '../shared/tweets/tweets.service';
import { NgForm } from '@angular/forms';
import { AuthService } from '../auth.service'

@Component({
selector: 'app-tweets-add',
templateUrl: './tweets-add.component.html',
styleUrls: ['./tweets-add.component.css']
})
export class TweetsAddComponent implements OnInit {

tweet: any = {};

constructor(private route: ActivatedRoute,
private router: Router,
private tweetsService: TweetsService,
private authService: AuthService) { }

ngOnInit() {
}

gotoList() {
this.authService.checkCredentials();
this.router.navigate(['/tweets-list']);
}

save(form: NgForm) {
this.authService.checkCredentials();
this.tweetsService.save(form).subscribe(result => {
this.gotoList();
}, error => console.error(error));
}

}

TweetsAddComponent will use an injected TweetsService to save a tweet submitted by a logged in User. On success, it will redirect to the Tweets List.

tweets-add.component.html will look like the following after modifying the stub code:

<mat-card>
<form #tweetsForm="ngForm" (ngSubmit)="save(tweetsForm.value)">
<mat-card-header>
<mat-card-title><h2>Add Tweet</h2></mat-card-title>
</mat-card-header>
<mat-card-content>
<mat-form-field>
<textarea matInput placeholder="Tweet"
[(ngModel)]="tweet.content" required name="content"
#content cols="50" rows="10"></textarea>
</mat-form-field>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" type="submit"
[disabled]="!tweetsForm.form.valid">Save</button>
<a mat-button routerLink="/tweets-list">Cancel</a>
</mat-card-actions>
<mat-card-footer>
</mat-card-footer>
</form>
</mat-card>

The preceding source code uses mat-* elements to structure the layout of the Tweets Add page. It also has a ngForm, which uses the TweetsAddComponent.save method to submit a tweet to the backend by invoking the API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.66.178