Explicitly showing error messages when page initially loads - javascript

<mat-form-field>
<mat-label></mat-label>
<input [required] = "isMandatory? true:false" placeholder="Just a placeholder">
<mat-error *ngIf="isMandatory">mandatory field</mat-error>
</mat-form-field>
The above code is working fine and showing the error message when the textbox gets dirty or in focus. Now, I am trying to show before hand when the page loads initially.
<input [required] = "isMandatory? true:false" placeholder="Just a placeholder"
ng-model-options="{ updateOn: 'change blur' }">
Tried above approach with no luck. Is there any way to show error messages when form initially loads? Thanks!

One way to achieve this would be to add the following code inside ngOnInit():
ngOnInit(): void {
// FormControl or FormGroup initialization code
// ....................................
this.yourControl.markAsTouched();
// OR, if you want for the whole formGroup (and your're using at leat Angular 8)
this.yourFormGroup.markAllAsTouched();
}
This should do the trick and show the client side errors (required in your case) upfront.

Related

Angular7 Detect change of input value in reactive forms

I am working for the first time with reactive forms in Angular(v7)
I want to make my submit button enabled if any of the fields has changed. So I am working with the dirty value of the form.
For a simple scenarios its working. I change a input type text and the button became enable.
But now I got a problem with an element (<span id="locationUpdated">) that the value inside of it is being changed by the result of some other javascript functions.
So I decided to listening the change of an hidden input that get the value the same way as the span element
<form [formGroup]="model.form" >
....
<input id="nameInput" type="text"
[(ngModel)]="model.user.name"
formControlName="name" />
...
<span [textContent]="model.user.location.label" id="locationUpdated"></span>
<input type="hidden" [value]="model.user.location.label" formControlName="location" />
....
<button [ngClass]="{'disabled': !model.form.dirty}></button>
</form>
--- Component ---
private buildFormUpdated() {
this.model.form = this.formBuilder.group({
name: [this.model.user.name, [Validators.required]],
location: [this.model.user.location.label]
});
}
I replace the hidden to text so I can see the value change and it is working fine.
However the property dirty continues false. If I change manually I get the dirty:true
What am I missing?
Thanks
What am I missing?
The dirty flag is not set to true when the data is changed programatically.
It is set to true only if the user blurs the control component, or changes the value (through the UI)
Please ref official docs - https://angular.io/guide/form-validation#why-check-dirty-and-touched
you can explicit marks the control as dirty by doing this after your logic
this.model.form.markAsDirty();

How to get the HTML of selected elements using TypeScript?

I am running an Ionic 2 app with TypeScript and I need to get the HTML of the items, selected by the mouse, when clicking a specific button.
I have tried different solutions, but none of these seemed to work. This is important because I should be able to retrieve an image URL in case an image is included in the selected text.
With my current solution, images are not even shown in the text selection.
How could I make it work in TypeScript? I have tried replacing document.selection to .getSelection() etc, but without any luck.
HTML
<p>test <b>ok</b> <img src="./test.jpg" /> </p>
When Ok and the image are selected, the output should be
<b>ok</b> <img src="./test.jpg" />
I think you are thinking of this in a "jquery way". If you want operations on the image in your component you need to add [] to the attribute that you want to effect.
For example, because you want a dynamic image you need to apply property bindings ,which you can use in you component as a method or a variable. So you can add functionality on the image tag with a method on the src attribute directly
<img [src]="image()" />
And in the component you add
image(){
//
}
Or assign it, so that when the action occurs that assigns the image to the image tag then assign it to a variable
<img [src]="imageScr" />
<button ion-button (click)="onImageUpload()"> Add </button>
Component
imageSrc:string = 'http://placehold.it/350x150';
constructor(...){}
onImageUpload(){
let uploadedImage = // get image stuff here
this.imageScr = uploadedImage;
}
Without going too much off topic I would suggest that you create an angular reactive form to your input types. This creates a better structure with baked in functionality that helps with most functionality that you need. So instead of a property binding you add a formControlName with your formGroup holding all the form input values.
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
export class ImagePage{
imageUploadForm: FormGroup;
imagePattern:string = '(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?'
constructor(public navCtrl: NavController, public navParams: NavParams,
public formBuilder: FormBuilder ){
this.imageUploadForm = this.formBuilder.group({
image:['http://placehold.it/350x150',[Validators.required,Validators.pattern(this.imagePattern)]]
imageName:[''[Validators.required]]
})
}
}
And then in your Html
<form [formGroup]="imageUploadForm" novalidate>
<ion-item>
<ion-img width="80" height="80" [src]="imageUploadForm.get('image').value"></ion-img>
<input type="file" name="pic" accept="image/*" formControlName="image">
</ion-item>
<ion-item class="item-error" >
<ion-label *ngIf="imageUploadForm.get('image').errors?.required"> Image is required </ion-label>
<ion-label *ngIf="imageUploadForm.get('image').errors?.pattern"> Image file must end in .jpg, .png or gif </ion-label>
</ion-item>
...
So now all the functionality that you want is controlled in the reactive form as a formControl in a formGroup which i think allows for a much greater flexibility as well as a better defined group of code
You can view the official documentation on reactive forms here

Angular2: how do display character count on reactive form input

I'm using Angular2 reactive forms, and I want to display a character count of a textarea as the user types.
I was hoping to just be able to include the form control's name.length in my html like so:
<div class="form-group">
<label for="incidentDescription">Brief Description of Incident</label>
<textarea id="incidentDescription" formControlName="incidentDescription" required [attr.maxLength]="maxIncidentDescriptionLength"></textarea>
<small><code>{{alaynaPage.incidentDescription.length}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
</div>
This "works" however the length of the form control lags one keystroke behind. So for example if I type a into the textarea {{alaynaPage.incidentDescription.length}} is 0. If i then type b (so string is ab) {{alaynaPage.incidentDescription.length}} is now 1.
How do I get this to work as expected?
I got it to work via a hack but there has to be an easier way:
//in component:
theLength: number = 0;
ngOnInit(): void {
this.buildForm();
(this.alaynaPageForm.controls['incidentDescription'] as FormControl).valueChanges.subscribe(value => {
// do something with value here
this.theLength = value.length;
});
}
//in my html:
<small class="form-text text-muted"><code>{{theLength}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
You just need to use a template reference variable
<textarea id="incidentDescription" formControlName="incidentDescription" #incidentDescription></textarea>
<small class="form-text text-muted"><code>{{incidentDescription.value.length}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
You want a hack, here's the hack. Use this:
{{alaynaPageForm.value?.incidentDescription?.length}}

jQuery validation plugin: hide error messages when entering content

In many forms I am developing with jQuery validation plugin I have many fields to fill like the following:
<p>
<label>Nome</label>
<span class="field">
<input type="text" name="nome" id="nome" class="smallinput"" value=""/>
</span>
</p>
and these fields are declared as required and if they are empty a message error is correctly shown. After that I would like the error message to hide when the user enters information. However, this does not happen. How can I set this? Moreover I have some fields which should contain email addresses whose rule is
email:{
required: true,
email: true,
},
and it happens that some email addresses are claimed to be not valid while instead they are. Is there a way to fix this?
SOLUTION
For those who might be interested, what I have tried is to add a class "req" to span elements which are required and when the user types in something and the value changes and is different from the void string, then an attribute style is added to generated label error, like that:
jQuery(".req").on('input',function(){
if (this.value != "")
jQuery(this).find("label").attr('style','display:none !important');
});
This seems to work fine. Obviously, if the value becomes again void then the red label error message is shown again.

Problems with knockout-validation custom message template

I've not used Knockout Validation and I'm trying to get a feel for what can be done with it.
I'm trying to figure out if it is possible to display an icon rather than an error message to the right of an input tag when there is an error. And, if the user hovers over the icon, the error message is displayed.
Has anyone done this or have an idea of how to accomplish this?
Thanks.
EDIT: (more detailed example of what I'm trying to do)
Say I have the following in my view model:
var firstName = ko.observable().extend({required: true});
My HTML:
<input data-bind="value: firstName" />
My understanding is that if the first name textbox were left blank, then (by default) some text would be displayed to the right of the textbox stating that this field is required.
What I'm trying to understand is how to change the default behavior of displaying error text on the right to displaying an icon on the right which, when hovered over, will popup the error message.
So, a start would be something like:
<div data-bind="validationOptions: {messageTemplate: 'myCustomTemplate'}">
<input data-bind="value: firstName" />
<input data-bind="value: lastName" /> //also required
</div>
<div id='myCustomTemplate'>
//This icon should only display when there is an error
<span class="ui-icon ui-icon-alert" style="display: inline-block"/>
//css/javascript would display this when user hovers over the above icon
<span data-bind="validationMessage: field" />
</div>
I have no clue if I'm using the messageTemplate feature correctly. I also wouldn't know what to bind the text to in the customTemplate in order to display the correct error message for each error. IOW, firstname and lastname could have custom error messages. If they are both using the same template, how does the template accomodate the custom error message?
I hope that makes sense.
It is possible to show an icon and to display the error message on hovering.
In one project we are doing something similar. We show a badge with a error number, but we use decorateElement to highlight the fields and errorsAsTitleOnModified to show the errors when hovering over the input.
To create a error messageTemplate you should wrap your template in a script tag. It works like templates of the ko template binding.
Inside the template you can access the validated observable by referring to 'field'. The error message is stored in the property 'error' of your observable.
<script type="text/html" id="myCustomTemplate">
<span data-bind="if: field.isModified() && !field.isValid(),
attr: { title: field.error }">X</span>
</script>
I have created a fiddle to show this in action: http://jsfiddle.net/nuDJ3/180/

Categories

Resources