If click submit data send ng2-file-upload - api

How can I make the images uploads go with the data when I click the send button. Now I have a problem in the fact that when you select images are immediately downloaded to the server and there is a post request to api. I use Rails 5 for api
gallery.component.ts
name: string;
uploadFile: any;
hasBaseDropZoneOver: boolean = false;
uploadedFiles: any[] = [];
options: Object = {
url: 'http://localhost:3000/galleries'
};
sizeLimit = 2000000;
handleUpload(data): void {
if (data && data.response) {
data = JSON.parse(data.response);
this.uploadFile = data;
this.name = this.uploadFile.filename;
}
}
fileOverBase(e:any):void {
this.hasBaseDropZoneOver = e;
}
beforeUpload(uploadingFile): void {
if (uploadingFile.size > this.sizeLimit) {
uploadingFile.setAbort();
alert('File is too large');
}
}
shop.component.ts
id : number;
owner_id :number;
submit(user){
user.owner_id= this.authTokenService.currentUserData.id;
        this.httpService.postData(user)
              .subscribe((data) => {this.receivedUser=data; this.done=true;this.router.navigate(['/profile'])});
    }
ngOnInit() {
this.getUserShops(this.authTokenService.currentUserData.id)
.subscribe((ownerShops) => {
if (ownerShops.length > 0) {
// User has at least 1 shop
this.router.navigate(['/profile'])
console.log(ownerShops.id);
} else {
// User has no shops
}
})
}
shop.component.html
Name
<div class="form-group">
<label>About</label>
<input class="form-control" type="text" name="about" [(ngModel)]="user.about" />
</div>
<div class="form-group">
<label>opening</label>
<input class="form-control" type="text" name="opening" [(ngModel)]="user.opening" />
</div>
<div class="form-group" >
<label>closing</label>
<input class="form-control" type="text" name="closing" [(ngModel)]="user.closing" />
</div>
<app-gallery> </app-gallery>
<div class="form-group">
<button class="btn btn-default" (click)="submit(user)">Send</button>
</div>
gallery.component.html
<input type="file"
ngFileSelect
[options]="options"
(onUpload)="handleUpload($event)"
(beforeUpload)="beforeUpload($event)"
multiple>

Related

In my creation process I want to write to another entity than only the used

If I submit the page the first save goes without a problem
Than I assigned all values to the other entity which I want to write to create there a new record.
Why do I get an System Null Reference. I have in all fields the values which I want?
[
=== here is my c# Code ===========
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WorkCollaboration.Data;
using WorkCollaboration.Models;
namespace WorkCollaboration.Pages.TimeReports
{
public class CreateModel : PageModel
{
private readonly WorkCollaboration.Data.WorkCollaborationContext _context;
public CreateModel(WorkCollaboration.Data.WorkCollaborationContext context)
{
_context = context;
}
public IActionResult OnGet()
{
CusContactDropDownDisp = _context.CusContactDropDown.ToList(); // Added for DropDown
SupContactDropDownDisp = _context.SupContactDropDown.ToList(); // Added for DropDown
return Page();
}
[BindProperty]
public TimeReport TimeReport { get; set; }
public IEnumerable<Models.CusContactDropDown> CusContactDropDownDisp { get; set; }
public IEnumerable<Models.SupContactDropDown> SupContactDropDownDisp { get; set; }
public Models.PointsforSupContact PointsforSupContact { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
TimeReport.TimeReportSupContactPointValue = (TimeReport.TimeReportHours * 10);
_context.TimeReport.Add(TimeReport);
await _context.SaveChangesAsync();
//============================================
// Adding new Point Record to Supplier Contact
//============================================
PointsforSupContact.PointsId = TimeReport.TimeReportId;
PointsforSupContact.PointsSupContactId = TimeReport.TimeReportSupplierTalentContactId;
PointsforSupContact.PointsInternalUserId = 1; // User 1 Christof Oberholzer must be entered in Contacts and User
PointsforSupContact.PointsDate = TimeReport.TimeReportDate;
PointsforSupContact.PointsTotal = TimeReport.TimeReportSupContactPointValue;
PointsforSupContact.PointsText = TimeReport.TimeReportText;
PointsforSupContact.PointsTitle = "TimeReporting Points";
_context.PointsforSupContact.Add(PointsforSupContact);
await _context.SaveChangesAsync();
return RedirectToPage("/TimeReportOverview/Index");
}
}
}
==== My Page ======
#page
#using Microsoft.AspNetCore.Localization
#using Microsoft.AspNetCore.Mvc.Localization
#model WorkCollaboration.Pages.TimeReports.CreateModel
#{
ViewData["Title"] = "Create";
ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
}
#inject IViewLocalizer Localizer
<h1>Create</h1>
<h4>TimeReport</h4>
<p>
<a asp-page="/TimeReportOverview/Index">Back to Index</a>
</p>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="TimeReport.TimeReportSupContactPointValue" value="0"/>
<div class="form-group">
<label asp-for="TimeReport.TimeReportId" class="control-label"></label>
<input asp-for="TimeReport.TimeReportId" value='#ViewData["RandomId"]' readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportCustomerNeedContactId" class="control-label"></label>
</div>
<select id="CusContactId" asp-for="CusContactDropDownDisp" asp-items="#(new SelectList(Model.CusContactDropDownDisp,"CusContactId","CusFullName"))">
<option value="" selected disabled>--Choose Customer--</option>
</select>
<div class="form-group">
<input asp-for="TimeReport.TimeReportCustomerNeedContactId" readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportCustomerNeedContactId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportSupplierTalentContactId" class="control-label"></label>
</div>
<select id="SupContactId" asp-for="SupContactDropDownDisp" asp-items="#(new SelectList(Model.SupContactDropDownDisp,"SupContactId","SupFullName"))">
<option value="" selected disabled>--Choose Supplier--</option>
</select>
<div class="form-group">
<input asp-for="TimeReport.TimeReportSupplierTalentContactId" readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportSupplierTalentContactId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportDate" class="control-label"></label>
<input type="datetime-local" asp-for="TimeReport.TimeReportDate" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportHours" class="control-label"></label>
<input asp-for="TimeReport.TimeReportHours" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportHours" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportText" class="control-label"></label>
<input asp-for="TimeReport.TimeReportText" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportText" class="text-danger"></span>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TimeReport.TimeReportState, htmlAttributes: new { #class = "form-group" })
<div class="form-group">
#Html.DropDownListFor(model => model.TimeReport.TimeReportState, new List<SelectListItem>
{
new SelectListItem {Text = "Gebucht", Value = "Reported", Selected = true },
new SelectListItem {Text = "Kontrolliert", Value = "Controlled" },
new SelectListItem {Text = "Verrechnet / Noch nicht bezahlt", Value = "Invoiced / Not yet payed" },
new SelectListItem {Text = "Verrechnet / Bezahlt", Value = "Invoiced / Payed" },
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TimeReport.TimeReportState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
Back to List
</div>
</form>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script>
$("#CusContactId").on("change", function () {
$("#TimeReport_TimeReportCustomerNeedContactId").val($("#CusContactId").val());
});
$("#SupContactId").on("change", function () {
$("#TimeReport_TimeReportSupplierTalentContactId").val($("#SupContactId").val());
});
</script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Thank you for your help
First In your view:
ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
GetHashCodemethod make the Guid to int,please make sure it matches the type in your model.
Then the right way to add new PointsforSupContact is to create a new PointsforSupContact,so you need to delete the code:
public Models.PointsforSupContact PointsforSupContact { get; set; }
and change you code to:
//...
await _context.SaveChangesAsync();
//add this line
var PointsforSupContact=new PointsforSupContact();
PointsforSupContact.PointsId = TimeReport.TimeReportId;
//...

Angular prefilled form data becomes null when submitting

I have created an Angular form to update the user details. The fields values of the form are filled by the user details fetched from the backend when the form loads. If the user wishes to update any field they can update and submit the form. But the field values of the fields which user didn't change are set as null even though those fields are initialized at the beginning. Can someone please explain how to get the prefilled unchanged field values when submitting the form?
The HTML file is this,
<app-navbar></app-navbar>
<div class="container">
<form [formGroup]="profileForm" style="margin-top: 60px;" disabled="true" (ngSubmit)="onSubmit()">
<input type="file" id="file" (change)="onFileSelected($event)" accept="image\jpeg" formControlName="profPic">
<div class="row">
<!--Profile Picture-->
<div class="col-12 col-md-4 d-flex justify-content-center">
<label for="file">
<a (mouseenter)="hoverIdx = 1"
(mouseleave)="hoverIdx = -1"
id="overlay">
<span [ngClass]="{ 'overlay-icon': true, 'hide': hoverIdx !== 1 }"
class="rounded-circle">
<fa-icon [icon]="cameraIcon" class="icon"></fa-icon>
</span>
<img
[src]="profPic"
class="rounded-circle"
width="300"
height="300"
/>
</a>
</label>
<div class="col-md-2 align-self-end ml-auto p-2" id="deleteIcon">
<fa-icon [icon]="deleteIcon"></fa-icon>
</div>
</div>
<div class="col-12 col-md-8">
<div class="card" style="margin-bottom: 20px;">
<div class="card-body" >
<!---Intro-->
<div class="row" style="font-size: 60px;">
<div class="col-12">Hi, {{ fNme }}</div>
</div>
<!--first name & last name-->
<div class="row" style="margin-top: 10px;">
<div class="col-12 col-md-6">
<mat-form-field appearance="outline">
<input formControlName="fName"
matInput placeholder="First Name"
[value]="fNme"
(change)="fNmeChnge = true"/>
</mat-form-field>
</div>
<div class="col-12 col-md-6">
<mat-form-field appearance="outline">
<input formControlName="lName"
matInput placeholder="Last Name"
[value]="lNme"
(change)="lNmeChnge = true" />
</mat-form-field>
</div>
</div>
<!--row-->
<!-- email & country-->
<div class="row" style="margin-bottom: 25px;">
<div class="col-12 col-md-6">
<mat-form-field appearance="outline">
<input formControlName="email"
matInput placeholder="Email"
[value]="email"
(change)="emailChnge = true"/>
</mat-form-field>
</div>
<div class="col-12 col-md-6">
<mat-form-field appearance="outline" >
<input formControlName="country"
matInput placeholder="Country"
[value]="country"
(change)="countryChnge = true"/>
</mat-form-field>
</div>
</div>
<!--row-->
</div>
</div>
<button type="button" class="btn btn-primary float-right" style="margin-left:10px" type="submit">Save</button>
<button type="button" class="btn btn-outline-primary float-right" (click)="cancel()">Cancel</button>
</div><!--col-md-8-->
</div><!--row-->
</form>
</div><!--container-->
The component file is this,
import { User } from './../shared/user.model';
import { F_NAME, L_NAME, AUTHENTICATED_USER, PROF_PIC, BASE64URL } from './../../app.constants';
import { Component, OnInit, Inject } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { AuthenticationService } from '../service/authentication.service';
import { MAT_DIALOG_DATA, MatDialogRef, MatDialog } from '#angular/material/dialog';
import { DialogOverviewExampleDialog } from './dialog';
import { faCamera, faTrashAlt } from '#fortawesome/free-solid-svg-icons';
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: User;
cameraIcon = faCamera;
deleteIcon = faTrashAlt;
profPic: any;
profileForm: FormGroup;
email: string;
fNme: string;
lNme: string;
country: any;
selectedFile: File = null;
base64Data: any;
fNmeChnge: any;
lNmeChnge: any;
countryChnge: any;
emailChnge: any;
title = 'Profile';
constructor(
private service: AuthenticationService,
public dialog: MatDialog,
private sanitizer: DomSanitizer
) {
}
ngOnInit() {
this.email = sessionStorage.getItem(AUTHENTICATED_USER);
this.profileForm = new FormGroup({
fName: new FormControl(null, [Validators.required]),
lName: new FormControl(null, Validators.required),
email: new FormControl(null, [Validators.required, Validators.email]),
country: new FormControl(null, Validators.required)
});
this.service.getUser(this.email)
.subscribe(res => {
this.fNme = res.fNme;
this.lNme = res.lNme;
this.country = res.country;
this.profPic = BASE64URL + res.profPic ;
});
}
openDialog(): void {
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
width: '500px'
});
}
onFileSelected(event){
this.selectedFile = event.target.files[0] as File;
const reader = new FileReader();
reader.onload = e => this.profPic = reader.result;
reader.readAsDataURL(this.selectedFile);
}
onSubmit() {
const fd = new FormData();
fd.append('file', this.selectedFile);
this.service.uploadImage(fd, this.email);
this.user = new User(this.profileForm.get('fName').value,
this.profileForm.get('lName').value,
this.profileForm.get('country').value,
this.profileForm.get('email').value);
console.log(this.user);
this.service.updateProfile(this.user, this.email);
// .subscribe(res => {
// this.fNme = res.fNme;
// this.lNme = res.lNme;
// this.country = res.country;
// this.profPic = BASE64URL + res.profPic ;
// });
this.ngOnInit();
}
I gets the user data from the server via these codes,
uploadImage(file: FormData, email: string) {
this.http.put<any>(`${API_URL}/profile-picture/${email}`, file)
.subscribe(res => {console.log(res); });
}
updateProfile(user: User, email: string) {
this.http.put<any>(`${API_URL}/profile/${email}`, user).subscribe();
}
getUser(email: string) {
return this.http.get<any>(`${API_URL}/user/${email}`);
}

How to show success message in vue js after inserting the date into database

I have a perfectly working form I can insert data into database using axios after form validation. I am just struggling to show a success message after inserting the data into the database. how to hide the form and display a succcess message in the same section after sending the data into the database??
here's my perfectly working code
<template>
<b-container>
<div class="update-info">
<div class="feature-text myinv-title">
<h5 class="title title-sm">Update your information</h5>
</div>
<div>
<form #submit.prevent="submit">
<p v-if="errors.length">
<b>Please fill in all the fields</b>
<ul>
<li v-for="error in errors" class="alert alert-danger">{{ error }}</li>
</ul>
</p>
<div class="form-row">
<div class="form-group col-md-3">
<label for="trx number">TRX No</label>
<input
type="text"
name="trx Number"
v-model="newUser.trx"
class="form-control trx-address-nooverflow"
placeholder="Copy paste your TRX no"
/>
<b-form-text id="input-formatter-help">
<a class="text-success">Your TRX address: {{trxNo}}</a>
</b-form-text>
</div>
<div class="form-group col-md-3">
<label for="name">Name</label>
<input
type="text"
name="name"
v-model="newUser.name"
class="form-control"
placeholder="Enter you name"
/>
</div>
<div class="form-group col-md-3">
<label for="email">Email</label>
<input
type="text"
name="email"
v-model="newUser.email"
class="form-control"
placeholder="Enter valid email address"
/>
</div>
<div class="form-group col-md-3">
<label for="country">Country</label>
<country-select
id="Country"
v-model="newUser.country"
:country="newUser.country"
topCountry="US"
class="form-control"
/>
</div>
<div class="form-group col-md-3">
<label for="mobile">Mobile No</label>
<input
id="mobile"
class="form-control"
v-model="newUser.mobile_no"
type="text"
placeholder="Enter your mobile no."
/>
<b-form-text id="input-formatter-help">
Please enter valid phone number
</b-form-text>
</div>
<div class="form-group col-md-3">
<div class="top-30">
<input type="submit" class="btn btn-btn btn-grad btn-submit" />
</div>
</div>
</div>
</form>
</div>
</div>
</b-container>
</template>
here's my vue js code
<script>
import axios from 'axios'
export default{
data(){
return{
errorMessage: "",
successMessage: "",
text: "success",
errors: [],
users: [],
newUser: {trx: "", name: "", country: "", email: "", mobile_no: ""}
}
},
computed: {
trxNo: function() {
return this.$store.state.myAddress;
}
},
mounted: function(){
this.getAllUsers();
},
methods:{
getAllUsers: function(){
axios.get('https://onex.tronpayer.com/api/update-info-form.php?action=read', { crossdomain: true })
.then((response) => {
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.users = response.data.users;
}
});
},
submit(){
this.checkForm()
if(!this.errors.length) {
var formData = this.toFormData(this.newUser);
axios.post('https://onex.tronpayer.com/api/update-info-form.php?action=update', formData, { crossdomain: true })
.then((response) => {
this.newUser = {trx: "", name: "", country: "", email: "", mobile_no: ""};
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.getAllUsers();
}
});
}
},
toFormData: function(obj){
var form_data = new FormData();
for(var key in obj){
form_data.append(key, obj[key]);
}
return form_data;
},
clearMessage: function(){
this.errorMessage = "";
this.successMessage = "";
},
//validation
checkForm: function (e) {
this.errors = [];
if (!this.newUser.trx) {
this.errors.push("Trx Number Required.");
}
if (!this.newUser.name) {
this.errors.push("Name Required.");
}
if (!this.newUser.country) {
this.errors.push("Country Required.");
}
if (!this.newUser.email) {
this.errors.push('Email Required.');
} else if (!this.validEmail(this.newUser.email)) {
this.errors.push('Valid Email Address Required.');
}
if (!this.newUser.mobile_no) {
this.errors.push("Mobile Number Required.");
}
if (!this.errors.length) {
return true;
}
},
validEmail: function (email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}
}
</script>
You can use the v-if conditional rendering for disabling the form and showing the message.
https://v2.vuejs.org/v2/guide/conditional.html
Just create a variable like savingSuccessful: false and set it to true when your ajax request was successful.
Use it now in your form like
<form #submit.prevent="submit" v-if="!savingSuccessful">
This means your form will be displayed until your variable is true.
For a success-message you can create something like this:
<div class="success" v-if="savingSuccessful">
{{ this.text }}
</div>
Your message will be rendered when the variable is true.
Here a JSFiddle:
https://jsfiddle.net/MichelleFuchs/nydruxzw/2/

Aurelia custom element access data from child to parent view model

I am new to Aurelia and need help accessing values from custom element in another view.
I have a scenario where I would like to share input file for attachment in multiple forms. One of the approach I am taking is to create custom element for input files that can be shared with multiple forms in web application.
Below is my code:
Custom element called FilePicker which will be shared between multiple forms. In my Request paged I inserted the custom element called:
<file-picker router.bind="router" accept="image/*" multiple="true" ></file-picker>
My requirement is to access property called validFiles which is an array. I would like to use values from validFiles to custom object in Request view model called formData['attachment']
TS:
import { customElement, useView, bindable, bindingMode } from 'aurelia-framework';
#customElement('file-picker')
#useView('./file-picker.html')
export class FilePicker {
#bindable accept = '';
#bindable multiple = false;
#bindable({ defaultBindingMode: bindingMode.twoWay }) files: FileList;
validFiles = [];
input: HTMLInputElement;
// Validate function for on change event to input file.
public filesChanged() {
if (!this.files) {
this.clearSelection();
}
if (this.files) {
this.processFiles();
}
}
// Trigger on button click
public triggerInputClick() {
this.input.click();
}
// Find value in array of object
private findValinArrObj(arr, key, val) {
return arr.map(function (v) { return v[key] }).indexOf(val);
}
// Process file for each new files uploaded via browser
private processFiles() {
if (this.files) {
for (let i = 0; i < this.files.length; i++) {
let findFile = this.findValinArrObj(this.validFiles, 'name', this.files.item(i).name);
if (findFile === -1) {
this.validFiles.push(this.files.item(i));
}
}
this.clearSelection();
}
}
// Remove file from fileNames and validFiles array
public removeByFileName(fileName) {
if (this.validFiles) {
for (let i = 0; i < this.validFiles.length; i++) {
if (this.validFiles[i].name === fileName) {
this.validFiles.splice(i, 1);
}
}
}
}
// Clear input file in DOM
private clearSelection() {
this.input.type = '';
this.input.type = 'file';
}
}
HTML:
<template>
<input type="file" accept.bind="accept" multiple.bind="multiple"
files.bind="files" ref="input"
style="visibility: hidden; width: 0; height: 0;">
<button class="btn btn-primary" click.delegate="triggerInputClick()">
<slot>Browse...</slot>
</button>
<ul class="list-group" if.bind="validFiles">
<li class="list-group-item" repeat.for="file of validFiles" style="padding: 0; border:none;">
${file.name} <span class="glyphicon glyphicon-remove text-danger" style="cursor: pointer;" click.delegate="removeByFileName(file.name)"></span>
</li>
</ul>
</template>
Parent View Model:
TS:
export class Request {
pageTitle: string = "Request Page";
title: string = '';
description: string = '';
businessValue: string = '';
emails: string = '';
formData: object = {};
public postData() {
this.formData['title'] = this.title;
this.formData['description'] = this.description;
this.formData['businessValue'] = this.businessValue;
this.formData['emails'] = this.emails;
this.formData['attachment'] = [];
console.log(this.formData);
}
}
HTML:
<template>
<require from="./request.css"></require>
<require from="../../resources/elements/file-picker"></require>
<div class="panel panel-primary">
<div class="panel-heading">${pageTitle}</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" value.two-way="title" class="form-control" id="title" placeholder="Brief one-line summary of the request">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<input type="text" value.two-way="description" class="form-control" id="description" placeholder="Detailed description of the request">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Business Value</label>
<div class="col-sm-10">
<input type="text" value.two-way="businessValue" class="form-control" id="description" placeholder="Description of how this offers business value">
</div>
</div>
<div class="form-group">
<label for="emails" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" value.two-way="emails" class="form-control" id="emails" placeholder="Provide email address">
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-sm-2 control-label">Attachment(s)</label>
<div class="col-sm-10">
<file-picker router.bind="router" accept="image/*" multiple="true" ></file-picker>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" class="btn btn-default pull-right" click.trigger="postData()">Submit</button>
</div>
</div>
</form>
</div>
</div>
</template>
Any help is really appreciated. :)
You can set up two-way-binding on your Request view, to bind the validFiles in your child view (file-picker) to a variable in your parent view (Request):
request.html:
<file-picker valid-files.two-way="validFiles"></file-picker>
request.ts:
public validFiles: File[];
file-picker.ts:
#bindable
public validFiles: File[];
This way any changes made to the validFiles object in either the child or the parent will update the object in both viewmodels.

How to add custom validator to reactive forms in Angular5

I have the following passwordvalidator which I don't know how to attach into the html. The way I am invoking it now it's not working loginForm.controls.password.errors.passwordValidator
See below in the actual code.
import { FormControl } from "#angular/forms";
export class PasswordValidator {
static getPasswordValidator() {
return function passwordValidator(control: FormControl): { [s: string]: boolean } {
// Write code here..
if (!control.value.match(/^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,})/)) {
return { invalidPassword: true };
}
return null;
}
}
}
Then this is how I am using it in login.ts
ngOnInit() {
this.loginForm = this.fb.group({
username: ['', [Validators.required, Validators.email]],
password: ['',
Validators.compose([
Validators.required,
PasswordValidator.getPasswordValidator()
]
)]
});
}
But can't find out how to add it to the formcontrol in login.html
<mat-form-field class="example-full-width">
<input id="password" formControlName="password" matInput placeholder="Password">
</mat-form-field>
<br>
<div *ngIf="loginForm.controls.password.invalid && (loginForm.controls.password.dirty || loginForm.controls.password.touched)"
class="alert alert-danger">
<div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.required">
You must fill out your password
</div>
<div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.passwordValidator && !loginForm.controls.password.errors.required">
Invalid email password
</div>
You should check if the key invalidPassword exist in errors of that controls or not like that
<mat-form-field class="example-full-width">
<input id="password" formControlName="password" matInput placeholder="Password">
</mat-form-field>
<br>
<div *ngIf="loginForm.controls.password.invalid && (loginForm.controls.password.dirty || loginForm.controls.password.touched)"
class="alert alert-danger">
<div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.required">
You must fill out your password
</div>
<div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.invalidPassword && !loginForm.controls.password.errors.required">
Invalid email password
</div>