1 import { Component } from '@angular/core';
2 import { Router } from '@angular/router';
4 import { FriendService } from '../shared';
7 selector: 'my-friend-add',
8 template: require('./friend-add.component.html'),
9 styles: [ require('./friend-add.component.scss') ]
11 export class FriendAddComponent {
15 constructor(private router: Router, private friendService: FriendService) {}
21 customTrackBy(index: number, obj: any): any {
25 displayAddField(index: number) {
26 return index === (this.urls.length - 1);
29 displayRemoveField(index: number) {
30 return (index !== 0 || this.urls.length > 1) && index !== (this.urls.length - 1);
33 removeField(index: number) {
34 this.urls.splice(index, 1);
40 const notEmptyUrls = this.getNotEmptyUrls();
41 if (notEmptyUrls.length === 0) {
42 this.error = 'You need to specify at less 1 url.';
46 if (!this.isUrlsRegexValid(notEmptyUrls)) {
47 this.error = 'Some url(s) are not valid.';
51 if (!this.isUrlsUnique(notEmptyUrls)) {
52 this.error = 'Urls need to be unique.';
56 const confirmMessage = 'Are you sure to make friends with:\n - ' + this.urls.join('\n - ');
57 if (!confirm(confirmMessage)) return;
59 this.friendService.makeFriends(notEmptyUrls).subscribe(
62 alert('Already made friends!');
64 alert('Made friends!');
71 private getNotEmptyUrls() {
72 const notEmptyUrls = [];
74 this.urls.forEach((url) => {
75 if (url !== '') notEmptyUrls.push(url);
82 // Use HTML validators
83 private isUrlsRegexValid(urls: string[]) {
86 const urlRegex = new RegExp('^https?://(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$');
87 urls.forEach((url) => {
88 if (urlRegex.test(url) === false) {
96 private isUrlsUnique(urls: string[]) {
97 return urls.every(url => urls.indexOf(url) === urls.lastIndexOf(url));