Validation not getting triggered when value is changed - aurelia

In Aurelia project, I have created a bootstrap modal that will allow users to enter email addresses. At first when the pop-up is triggered, it applies the validation fine. See below image. This is how it looks like when the pop-up is opened for the first time.
Once you enter the validate email address and click on add btn, I am resetting the value of this.setEmail to "" an empty string. So that way users can type new email address to add. But the validation rule that shows the message Email is required is no longer getting triggered. See below example:
See the Plunker link here. Once the page is loaded. Click on the + icon next to email input. It will open a bootstrap modal.
Below is the code and can be seen at above link as well:
email.ts
import { customElement, useView, bindable, bindingMode, inject, observable } from 'aurelia-framework';
import { ValidationRules, ValidationControllerFactory, Validator } from 'aurelia-validation';
#inject(ValidationControllerFactory)
#customElement('email')
#useView('./email.html')
export class Email {
#bindable public modalName: string;
#bindable public modalValue: string;
#bindable public emailAddress: string;
public emailAddresses = [];
#observable public setEmail: string;
public errorMessage: string;
emailController = null;
constructor(factory) {
this.setEmail = '';
this.emailController = factory.createForCurrentScope();
ValidationRules.ensure('setEmail')
.displayName('Email')
.required()
.email()
.on(this);
}
public bind() {
this.emailController.validate();
}
private joinEmails() {
this.emailAddress = this.emailAddresses.join(";");
}
private isUniqueEmail = (email: string) => {
return (this.emailAddresses.indexOf(email) === -1)
}
public addEmail() {
if (this.setEmail) {
if(!this.isUniqueEmail(this.setEmail))
{
this.errorMessage = "You must provide unique email address.";
return;
}
this.emailAddresses.push(this.setEmail);
this.joinEmails();
this.setEmail = '';
}
else
{
this.errorMessage = "You must provide an email address."
}
}
public setEmailChanged(newValue, oldValue) {
console.log({oldValue: oldValue, newValue: newValue});
}
public removeEmail(index) {
this.emailAddresses.splice(index, 1);
this.joinEmails();
console.log(this);
}
}
email.html
<template>
<!-- Modal -->
<div class="modal fade" id="${modalName}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add Email Address</h4>
</div>
<div class="modal-body">
<div class="input-group">
<input type="text" id="setEmail" name="setEmail" class="form-control" value.bind="setEmail & validateOnChangeOrBlur" />
<span class="input-group-btn">
<button class="btn btn-primary"
disabled.bind="emailController.errors.length > 0"
click.delegate="addEmail()">Add
</button>
</span>
</div>
<input type="text" value.bind="emailAddress" hidden />
<span class="text-danger" repeat.for="error of emailController.errors">${error.message}</span>
<span class="text-danger" if.bind="errorMessage">${errorMessage}</span>
<div>
<ul class="list-group" if.bind="emailAddresses.length > 0" style="margin-top: 10px;">
<li class="list-group-item" repeat.for="e of emailAddresses">
${e} <span class="glyphicon glyphicon-remove text-danger pull-right" style="cursor: pointer;" click.delegate="removeEmail($index)"></span>
</li>
</ul>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</template>

In your addEmail() function after the line this.setEmail = ''; call the validate again with this.emailController.validate();
The validate() method returns a Promise so you may want to handle any rejections as you would normally see this section of the validation docs Validation Controller specifically the sub section 'validate & reset'.
I'm guessing you expected this to happen automatically because of the 2-way binding and the validateOnChangeOrBlur binding behavior the reason it didn't is that the JavaScript setting the value doesn't trigger DOM events so you need to manually call or fire a synthetic event.

Related

ASP.NET Core Razor Page, code behind method not being triggered

I have a C# Razor Pages project.
I created a Login view in the following structure:
- Pages
- Account
- Login.cshtml
This is the code for my Login view
#page "{handler?}"
#model HAL_WEB.Pages.LoginModel
#{
Layout = "_LayoutLogin";
}
<section class="section register min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-4 col-md-6 d-flex flex-column align-items-center justify-content-center">
<div class="d-flex justify-content-center py-4">
<a href="index.html" class="logo d-flex align-items-center w-auto">
<img src="assets/img/teamtruetech_logo.png" alt="">
<span class="d-none d-lg-block">HAL Admin</span>
</a>
</div><!-- End Logo -->
<div class="card mb-3">
<div class="card-body">
<div class="pt-4 pb-2">
<h5 class="card-title text-center pb-0 fs-4">Login to Your Account</h5>
<p class="text-center small">Enter your username & password to login</p>
</div>
<form id="login-form" class="row g-3 needs-validation" novalidate>
<div class="col-12">
<label for="yourUsername" class="form-label">Username</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend"></span>
<input type="text" name="username" class="form-control" id="yourUsername" required>
<div class="invalid-feedback">Please enter your username.</div>
</div>
</div>
<div class="col-12">
<label for="yourPassword" class="form-label">Password</label>
<input type="password" name="password" class="form-control" id="yourPassword" required>
<div class="invalid-feedback">Please enter your password!</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" value="true" id="rememberMe">
<label class="form-check-label" for="rememberMe">Remember me</label>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary w-100" type="submit">Login</button>
</div>
#* <div class="col-12">
<p class="small mb-0">Don't have account? Create an account</p>
</div>*#
</form>
</div>
</div>
</div>
</div>
</div>
</section>
#section Scripts {
<script src="~/assets/js/loginpage.js"></script>
}
And this is the code behind:
using HAL_WEB.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
namespace HAL_WEB.Pages
{
public class LoginModel : PageModel
{
private readonly ApplicationDBContext _dbContext;
public LoginModel([FromServices] ApplicationDBContext dbContext)
{
_dbContext = dbContext;
}
public void OnGet()
{
}
public async Task<IActionResult> OnPostLoginAsync(string username, string password)
{
// Check if the provided credentials are valid
if (IsValidCredentials(username, password))
{
// If the credentials are valid, log the user in
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }, CookieAuthenticationDefaults.AuthenticationScheme)),
new AuthenticationProperties
{
IsPersistent = true, // Set this to true if you want the user to stay logged in after closing the browser
ExpiresUtc = DateTime.UtcNow.AddDays(7) // Set the expiration time for the cookie
});
// Redirect the user to the home page
return RedirectToPage("/Home");
}
else
{
// If the credentials are invalid, show an error message
ModelState.AddModelError(string.Empty, "Invalid username or password.");
return Page();
}
}
private bool IsValidCredentials(string username, string password)
{
// Replace this with your own validation logic
return username == "admin" && password == "password";
}
public IActionResult OnPostLoginTestAsync()
{
return new JsonResult(true);
}
}
In my Javascript file I tried to call the method OnPostLoginTestAsync or OnPostLoginAsync without success.
I'm getting a "Bad Request 400" error:
This is my Javascript Axios code for calling the method:
// Use Axios to send a POST request to the server with the form data
axios.post('/Account/Login?handler=login', {
username,
password,
})
.then((response) => {
// If the request is successful, redirect the page
window.location.href = '/home';
})
.catch((error) => {
// If there is an error, log it to the console
console.error(error);
});
Any clue what am I doing wrong? I'm going to /Account/Login?handler=login because the call is a Post and what I think is that the method OnPostLoginAsync should be executed.
UPDATE
I found something interesting, I created the following Get method:
public IActionResult OnGetTestAsync()
{
return new JsonResult(true);
}
And in my Javascript, I changed the Axios url to be:
axios.get('/Account/Login?handler=test')
.then(function (response) {
})
.catch(function (error) {
// Handle the error response
});
And I could get the method executed! But when I change the method name back to:
OnPostTestAsync
and my Axios to:
axios.post('/Account/Login?handler=test')
.then(function (response) {
})
.catch(function (error) {
// Handle the error response
});
It never gets executed and I get 400 Bad Request. Any clue?

How to collapse/expand Razor components using Blazor syntax?

I'm currently implementing a form to create a new user along with their respective user rights. In this form, I have about 30 different IT systems and if the user account should have the access rights for that specific IT system, I want to provide a panel to the admin where some extra information must be entered regarding that specific IT system. I want to implement this using razor components. What I have so far is the core view for my "new user form" as well as a razor component for the additional information of a specific IT system. By clicking the + button, I want the component to be visible / expand right below the IT system. That's what It looks like so far:
The new user form:
<div class="row">
<div class="col-sm-2 font-weight-bold">GOODWILL PKW/Smart</div>
<div class="col-sm-2">
<label>Add</label>
<input type="checkbox" />
</div>
<div class="col-sm-2">
<label>Change</label>
<input type="checkbox" />
</div>
<div class="col-sm-2">
<label>Remove</label>
<input type="checkbox" />
</div>
<div class="col-sm-4">
<button #onclick="#collapseGoodwill">+</button>
</div>
</div>
<ModalGoodwillPKW ></ModalGoodwillPKW>
#code {
public void collapseGoodwill() {
}
}
The component:
<div class="panel panel-default border">
<div class="panel-heading alert-primary">
<h3 class="panel-title">Goodwill PKW/smart</h3>
</div>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-sm-2 font-weight-bold">Profile</div>
<div class="col-sm-5">
<input type="checkbox" id="CB_c" />
<label>Salesman</label>
</div>
<div class="col-sm-5">
<input type="checkbox" id="CB_r" />
<label>Administrator</label>
</div>
</div>
</div>
</div>
</div>
Normally, I would use JQuery in the "collapseGoodwill" method to add a .collapse class to this element. But since I am experimenting with Blazor, I'd like to know if there is a 100% Javascript /JQuery free way of doing this.
Thanks!
Within Blazor, you always follow the pattern:
change data
--> new view rendered
Anytime you want to change the component's UI from outside, you should do it by changing the data (model/state/parameter/context/...).
As for this scenario, you can add a Collapsed field to indicate whether the panel itself is collapsed now:
<div class="panel panel-default border #Collapse">
<div class="panel-heading alert-primary">
<h3 class="panel-title">Goodwill PKW/smart</h3>
</div>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-sm-2 font-weight-bold">Profile</div>
<div class="col-sm-5">
<input type="checkbox" id="CB_c" />
<label>Salesman</label>
</div>
<div class="col-sm-5">
<input type="checkbox" id="CB_r" />
<label>Administrator</label>
</div>
</div>
</div>
</div>
</div>
#code{
[Parameter]
public string Collapse{get;set;}="collapse"; // hide by default
}
And whenever you want to collapse it, just set this parameter to collapse:
<div class="row">
<div class="col-sm-2 font-weight-bold">GOODWILL PKW/Smart</div>
<div class="col-sm-2">
<label>Add</label>
<input type="checkbox" />
</div>
<div class="col-sm-2">
<label>Change</label>
<input type="checkbox" />
</div>
<div class="col-sm-2">
<label>Remove</label>
<input type="checkbox" />
</div>
<div class="col-sm-4">
<button #onclick="e => this.Collapsed = !this.Collapsed">
#( this.Collapsed ? "+" : "-")
</button>
</div>
</div>
<ModalGoodwillPKW Collapse="#( this.Collapsed ? "collapse": "")" ></ModalGoodwillPKW>
#code {
private bool Collapsed = true;
}
Demo:
[Edit] : we can even refactor the above code to expose less information by changing the field from string to boolean.
The ModalGoodwillPKW.razor:
<div class="panel panel-default border #(Collapsed? "collapse": "" ) ">
<div class="panel-heading alert-primary">
<h3 class="panel-title">Goodwill PKW/smart</h3>
</div>
...
#code{
[Parameter]
public bool Collapsed{get;set;}= true; // hide by default
}
The UserForm.razor:
<div class="row">
...
<div class="col-sm-4">
<button #onclick="e => this.Collapsed = !this.Collapsed">
#( this.Collapsed ? "+" : "-")
</button>
</div>
</div>
<ModalGoodwillPKW Collapsed="#Collapsed" ></ModalGoodwillPKW>
#code {
private bool Collapsed = true;
}
I had a similar issue, I had a dynamic list of sections that I wanted to collapse, and I couldn't get the bootstrap data-toggle approach to work due to Blazor mis-handling of # anchor tags.
I used the component idea:
<div class="row">
#if (Collapsed)
{
<span #onclick="#Toggle" class="oi oi-plus mr-1"/>
}
else
{
<span #onclick="#Toggle" class="oi oi-minus mr-1"/>
}
#Title
</div>
#if(!Collapsed)
{
#ChildContent
}
#code {
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public bool Collapsed { get; set; }
[Parameter]
public string Title { get; set; }
void Toggle()
{
Collapsed = !Collapsed;
}
}
Which I could then use like this:
#foreach (var i in c.Request)
{
<Collapsable Title="#i.SectionName" Collapsed="true">
<ChildContent>
#foreach (var kvp in i.Values)
{
<div class="row">
<div class="col-1"></div>
<div class="col-6 font-weight-bolder">#kvp.Key</div>
<div class="col-5">#kvp.Value</div>
</div>
}
</ChildContent>
</Collapsable>
}
This seems to work well, each section is independently collapsible.
I've not tried it nested though.
Blazor "#Collapse" div with Bootstrap Toggle Button
I took #cjb110 's excellent sample code above and changed it to use a bootstrap badge button as the toggle, which is how I often add more verbose help info to a form field group, by hiding it behind a toggle and using a bootstrap or material info button for if a user wants it.
Component Part
Here's the component part, which you'd probably add to your Blazor solution's Client project's Shared folder as file name Collapsible.razor (note: Blazor component file names are to be capitalized--I think)
<div class="my-1">
<h3>#Title</h3>
#if (Collapsed)
{
<button #onclick="#Toggle" class="badge badge-info mr-2" role="button" >
#ButtonText
</button>
}
else
{
<button #onclick="#Toggle" class="badge badge-info mr-2" role="button" >
#ButtonText
</button>
}
<label>
#LabelText
</label>
</div>
#if(!Collapsed)
{
<div class="card alert alert-info mb-3" role="alert">
#ChildContent
</div>
}
#code {
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public bool Collapsed { get; set; }
//input params coming from from page
[Parameter]
public string Title { get; set; }
[Parameter]
public string ButtonText { get; set; }
[Parameter]
public string LabelText { get; set; }
void Toggle()
{
Collapsed = !Collapsed;
}
}
Template Part
I call this the "template" part. You can change the
Title text,
ButtonText,
I use these info-btn toggles typically in forms, so I added a
<label/> tag with LabelText.
In the <ChildContent/> area, in the component file I set it up as a Bootstrap alert class div, so it doesn't require a <p> tag, but put anything in here you want to show up when the toggle is opened.
<Collapsible
Title=""
ButtonText="Info"
LabelText="Search People & Assign Roles: "
Collapsed="true">
<ChildContent>
Find a person, add their role to the product (i.e.: Estimator, Foreman, Customer)
</ChildContent>
</Collapsible>
I was facing issues with the accordion collapse in my project.
This is how I fixed the bootstrap collapse issue in my Blazor app.
I simply copied these dependencies in the index.html file in Blazor webapp and it worked fine.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
Reference: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_collapsible&stacked=h
Let us know if this works for anyone else
There are some long and good answers. I thought I'd come in with the most important punchline, though.
You can hide whatever you want based on C# conditional logic. So you will VERY often use something like:
<div #onclick="()=>IsOpened = !IsOpened">Click on me to show the hidden control.</div>
#if (IsOpened){
<MyHiddenControl />
}
#code {
bool IsOpened;
}

Why still adding even with validation form?

When I click the button on my modal with an empty field on my input its give me an undefined value on my console. And when I put a value on my input and click the button it is adding to my database. The problem is even the empty field or the undefined value are also adding to my database and the sweetalert is not working. I want to prevent the empty field adding to my database and prevent the undefined. Can somebody help me?
//start of method
checkForm: function(e) {
if (this.category_description) {
return true;
}
this.errors = [];
if (!this.category_description) {
this.errors.push('Category required.');
}
e.preventDefault();
},
addCategory : function() {
axios({
method : "POST",
url : this.urlRoot + "category/add_category.php",
data : {
description : this.category_description
}
}).then(function (response){
vm.checkForm(); //for FORM validation
vm.retrieveCategory();
console.log(response);
swal("Congrats!", " New category added!", "success");
vm.clearData();
}).catch(error => {
console.log(error.response);
});
},
//end of method
<form id="vue-app" #submit="checkForm">
<div class="modal" id="myModal" > <!-- start add modal -->
<div class="modal-dialog">
<div class="modal-content " style="height:auto">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title"> Add Category </h4>
<button #click="clearData" type="button" class="close" data-dismiss="modal"><i class="fas fa-times"></i></button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<div class="col-lg-12">
<input type="text" class="form-control" id="category_description" name="category_description" v-model="category_description" placeholder="Enter Description">
<p v-if="errors.length">
<span v-for="error in errors"> {{ error }} </span>
</p>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit"#click="category_description !== undefined ? addCategory : ''" class="btn btn-primary"> Add Category </button>
</div>
</div>
</div>
</div>
</form>
The easiest way to stop this is adding data check. And condition check at top of your method.category_description !== undefined. Btw, move your e.preventDefault() to top too.
First of all do this:
- <button type="submit" #click="category_description !== undefined ? addCategory : ''" class="btn btn-primary"> Add Category </button>
+ <button type="submit" #click.prevent="addCategory" class="btn btn-primary"> Add Category </button>
and then in addCategory:
addCategory() {
if (!this.category_description) {
return;
} else {
// do your stuff here
}
}
When you are clicking on Add Category button, it is triggering the addCategory along with your validation method.
The return value of validation method has no impact on triggering of addCategory.
This issue can be handled in following ways.
Call addCategory only when there is some valid data
<button type="submit" #click="category_description != undefined ? addCategory() : ''" class="btn btn-primary"> Add Category </button>
Call the validation method inside addCategory and then proceed.

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.

Adding directives to simplify ngx-bootstrap modal

This is a suggestion to simplify the basic usages of ngx-bootstrap modal.
The idea is to use 2 directives:
bsDismissModal
replaces bootstrap data-dismiss="modal" attribute
works with "OK" button too, delaying the modal closing to pre-handle button click event
[bsToggleModal]="modalTemplate"
replaces both bootstrap data-toggle="modal" and data-target="#exampleModal" attributes
takes the ng-template reference as input value
Usage example:
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" [bsToggleModal]="exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<ng-template #exampleModal>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" bsDismissModal>×</button>
<h5 class="modal-title">Modal title</h5>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" bsDismissModal>Cancel</button>
<button type="button" class="btn btn-primary" (bsDismissModal)="save($event)">Save</button>
</div>
</div>
</div>
</div>
</ng-template>
A simple approach would be to use the BsModalService:
DismissModalDirective
import { Directive, EventEmitter, HostListener,
Inject, Output } from '#angular/core';
import { DOCUMENT } from '#angular/common';
import { BsModalService } from 'ngx-bootstrap/modal';
#Directive({
selector: '[dapDismissModal]'
})
export class DismissModalDirective {
// tslint:disable-next-line:no-output-rename
#Output('dapDismissModal') modalClosed = new EventEmitter<MouseEvent>();
private get modalsCount() {
return this.modalService.getModalsCount();
}
constructor(
private readonly modalService: BsModalService,
#Inject(DOCUMENT) private readonly document: Document
) {}
#HostListener('click', ['$event'])
hideModal(click: MouseEvent) {
this.modalClosed.emit(click);
if (click.defaultPrevented) {
return;
}
this.modalService.hide(this.modalsCount);
// Fix BsModalService
if (this.modalsCount === 0) {
this.document.body.classList.remove('modal-open');
}
}
}
(dismissModal)="handleClick($event)" replaces (click)="handleClick($event)", $event being the click MouseEvent.
Modal closing can be cancelled when preventing the click: event.preventDefault();.
ToggleModalDirective
import { Directive, HostListener, Input, TemplateRef } from '#angular/core';
import { BsModalService, ModalOptions } from 'ngx-bootstrap/modal';
#Directive({
selector: '[bsToggleModal]'
})
export class ToggleModalDirective {
// tslint:disable-next-line:no-input-rename
#Input('bsToggleModal') content: TemplateRef<any>;
#Input() bsModalConfig: ModalOptions;
constructor(private readonly modalService: BsModalService) {}
#HostListener('click')
showModal() {
this.modalService.show(this.content, this.bsModalConfig);
}
}