bstlboard-front/src/app/pages/submission/submission.page.ts

81 lines
2.2 KiB
TypeScript

import { Component, OnInit, ViewChild } from '@angular/core';
import { EntriesService } from '../../services/entries.service';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms';
@Component({
selector: 'page-submission',
templateUrl: './submission.page.html',
styleUrls: [ './submission.page.scss' ]
})
export class PageSubmission implements OnInit {
entryTypes: string[] = [ 'LINK', 'DISCUSSION', 'QUESTION', 'INTERN' ];
entryType: string = this.entryTypes[ 0 ];
working: boolean = false;
form: FormGroup;
@ViewChild('formDirective') private formDirective: NgForm;
constructor(private entriesService: EntriesService,
private router: Router,
private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.form = this.formBuilder.group({
entryType: [ '', Validators.required ],
url: [ '', Validators.required ],
title: [ '', Validators.required ],
text: [ '', Validators.nullValidator ],
});
this.form.get('entryType').setValue(this.entryType);
this.form.get('entryType').valueChanges.subscribe((value) => {
this.entryType = value;
if (value == 'LINK') {
this.form.get('url').setValidators([ Validators.required ]);
} else {
this.form.get('url').setValidators([ Validators.nullValidator ]);
}
});
}
hasError(controlName: string): boolean {
return this.form.controls[ controlName ].errors != null;
}
create(): void {
if (this.working) {
return;
}
this.working = true;
const entry: any = {};
entry.url = this.form.get("url").value;
entry.entryType = this.entryType;
entry.title = this.form.get("title").value;
entry.text = this.form.get("text").value;
this.entriesService.create(entry).subscribe((data) => {
this.router.navigateByUrl('/');
}, (error) => {
this.working = false;
if (error.status == 422) {
let errors = {};
for (let code of error.error) {
errors[ code.field ] = errors[ code.field ] || {};
errors[ code.field ][ code.code ] = true;
}
for (let code in errors) {
this.form.get(code).setErrors(errors[ code ]);
}
}
})
}
}