focus for ng-select not working Angular 5 - html

i'm trying to use focus for ng-select in angular 5 but its not working
i'm working with ng2-select
How to use focus for ng-select in Angular 5 ?
<label class="input">
<input (blur)="goTo()" type="text">
</label>
<label class="select" >
<div *ngIf="items.length > 0" >
<ng-select #select [items]="items">
</ng-select>
</div>
</label>
#ViewChild('select') myElement: ElementRef;
goTo(){
this.myElement.element.nativeElement.focus();
}

this works fine for me,
#ViewChild('ngSelect') ngSelect: NgSelectComponent;
ngAfterViewInit() {
if (this.autofocus) {
setTimeout(() => {
this.ngSelect.focus();
});
}
}
refer https://github.com/ng-select/ng-select/issues/762

Change this
goTo(){
this.myElement.element.nativeElement.focus();
}
to this,
import { ChangeDetectorRef } from '#angular/core';
constructor (private cRef: ChangeDetectorRef) {}
// import 'SelectComponent' from your library for 'ng2-select'
goTo(){
let el = null;
if (this.items.length > 0) {
this.cRef.detectChanges();
el = (this.myElement.nativeElement as SelectComponent).element.nativeElement.querySelector('div.ui-select-container > input');
if (el) { el.focus(); }
}
}
You may have to check if the element is defined or not (or if you need an extra 'nativeElement' in there, but I'm basically reusing the logic in here.
Just a cautionary note, this may not be a stable fix though if the library updates to rename these classes or modify the template.
Hope it helps.

A quick reply, in this solution,each select elements are recorded for future usage (and in this case , blur). This needs being adapted to your situation.
import { Component, OnInit } from '#angular/core';
import { ViewChildren, QueryList } from '#angular/core';
#Component({
selector: 'app-editor',
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.css']
})
export class EditorComponent implements AfterViewInit {
// Viewchildren
// https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
myindex:number;
#ViewChildren("select") inputs: QueryList<any>
constructor() {
this.myindex=0
}
// You will have to setup some input parameters in this function in order to switch to the right "select", (you have control)
private goTo()
{
// focus next input field
if (this.myindex +1 < this.inputs.toArray().length)
{
this.inputs.toArray()[this.myindex +1].nativeElement.focus();
this.myindex = this.myindex + 1;
}
else {
this.inputs.toArray()[0].nativeElement.focus();
this.myindex = 0;
}
}
private processChildren(): void {
console.log('Processing children. Their count:', this.inputs.toArray().length)
}
ngAfterViewInit() {
console.log("AfterViewInit");
console.log(this.inputs);
this.inputs.forEach(input => console.log(input));
// susbcribe to inputs changes, each time an element is added (very optional feature ...)
this.inputs.changes.subscribe(_ =>
this.processChildren() // subsequent calls to processChildren
);
}
}

A Simple way, you can do this also.
<label class="input">
<input (blur)="goTo(select)" type="text">
</label>
<label class="select">
<div *ngIf="items.length > 0">
<ng-select #select [items]="items">
</ng-select>
</div>
</label>
And in Typescript File.
goTo(select){
select.focus();
}

Related

Making a date field reactive in Angular

I'm trying to make a datepicker component from ngx-bootstrap a custom date-field, so that I can globalize some functionality and configs. But I can't seem to be able to catch the value of the Date object in the date input field.
My date-field.ts (I'm re-using some setup from a text-field. So bear with me if you see some remnants of the text field component. But I'm sure that my main problem is that my component doesn't know it's a date field)
import { Component, OnInit, forwardRef, Input } from '#angular/core';
import { FormControl, ControlValueAccessor, NG_VALUE_ACCESSOR } from '#angular/forms';
#Component({
selector: 'date-field',
templateUrl: './date-field.component.html',
styleUrls: ['./date-field.component.scss'],
providers:[
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => DateFieldComponent),
}
]
})
export class DateFieldComponent implements OnInit, ControlValueAccessor {
public dateField = new FormControl("")
private onChange: (name: string) => void;
private onTouched: () => void
#Input() name: string;
#Input() label: string;
#Input() required: boolean;
datepickerConfig = {
dateInputFormat: 'ddd, MMMM Do YYYY',
isAnimated: true,
adaptivePosition: true,
returnFocusToInput: true,
containerClass: 'theme-dark-blue'
}
constructor() { }
ngOnInit() { }
writeValue(obj: any): void {
const date = Date
this.dateField.setValue(new Date());
console.log(date);
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState?(isDisabled: boolean): void {
if (isDisabled) {
this.dateField.disable();
} else {
this.dateField.enable();
}
}
doInput() {
this.onChange(this.dateField.value)
}
doBlur() {
this.onTouched();
}
}
The template HTML:
<label
*ngIf="label"
for="{{name}}"
class="col-auto col-form-label {{required ? 'required' : '' }}">
{{label}}
</label>
<div class="col-expand relative">
<input
type="text"
class="form-control date-field"
#dp="bsDatepicker"
[formControl]="dateField"
(input)="doInput()"
(blur)="doBlur()"
ngModel
bsDatepicker
[bsConfig]="datepickerConfig"
required="{{required}}">
</div>
Using it in parent forms like this:
<date-field
name="dateChartered"
label="Date local union chartered"
formControlName="dateChartered"
required="true">
</date-field>
<p><strong>Date chartered is:</strong> {{dateChartered}}</p>
Assuming in your parent component you're correctly initializing FormGroup in controller and using it correctly in template, you have two main errors in your component.
First, as Belle Zaid says, you should remove ngModel from you custom datepicker's <input>.
Second, you are binding doInput() to (input), but it will fire only if you type in your input field, same for (change). You should bind to (bsValueChange) that's an output event exposed by BsDatepicker and it's safer, unless you plan to update value on user's input.
The resulting template will look like this:
<label *ngIf="label"
for="my-custom-datepicker"
class="col-auto col-form-label {{required ? 'required' : '' }}">
{{label}}
</label>
<div class="col-expand relative">
<input id="my-custom-datepicker"
type="text"
class="form-control date-field"
required="{{required}}"
bsDatepicker
[formControl]="dateField"
[bsConfig]="datepickerConfig"
(blur)="doBlur()"
(bsValueChange)="doInput()">
</div>
Once done the two changes you will notice an error in your console:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was
checked. Previous value for 'ng-pristine': 'true'. Current value: 'false'.. Find more
at https://angular.io/errors/NG0100
This is due to the fact that calling this.dateField.setValue(obj) in writeValue will also trigger (bsValueChange) and, thus, doInput(). To overcome this issue, you can edit your code like the following:
private componentInit = false;
// ...
doInput() {
if (!this.componentInit) {
this.componentInit = true;
return;
}
this.onChange(this.dateField.value);
}

Angular 6 input range validation

I have to validate one of the input element in my ngForm
How to validate range while submit that form
For example user should enter the price between $1000 to $2000
Please give the suggestions to proceed
Thanks
Try this
<form [formGroup]="myForm">
<label for="priceRange">Price Range: </label>
<input type="number" id="priceRange" formControlName="priceRange">
<div *ngIf="f.priceRange.errors">
Invalid Price Range
</div>
in component.ts
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '#angular/forms';
myForm = new FormGroup({});
get f() {
return this.myForm.controls;
}
constructor(private formBuilder: FormBuilder){
this.myForm = formBuilder.group({
priceRange: ['', [Validators.min(1000), Validators.max(2000)]]
});
}
Try this working Example
link
<h3>Reactive Forms Validator Example</h3>
<br>
<label>We have created two validators using slightly different approaches that validate if the input is equal to "A" or not.</label>
<br><br>
<label>Doesn't work because the method is not executed which will return the custom validator function.</label><br>
<input type="text" [formControl]="wrongOnlyA">
<br><br>
<label>Works because the method is executed.</label><br>
<input type="text" [formControl]="correctOnlyA">
<br><br>
<label>Works because the validator function is directly exported.</label><br>
<input type="text" [formControl]="onlyB">
.ts
import { Component, OnInit } from '#angular/core';
import { FormGroup } from "#angular/forms"
import { RxFormBuilder } from '#rxweb/reactive-form-validators';
import { FormBuilderConfiguration } from '#rxweb/reactive-form-validators';
import { EmployeeInfo } from '../employee-info.model';
#Component({
selector: 'app-employee-info-add',
templateUrl: './employee-info-add.component.html'
})
export class EmployeeInfoAddComponent implements OnInit {
employeeInfoFormGroup: FormGroup
constructor(
private formBuilder: RxFormBuilder
) { }
ngOnInit() {
let employeeInfo = new EmployeeInfo();
let formBuilderConfiguration = new FormBuilderConfiguration();
formBuilderConfiguration.validations = {
age : {
range : {minimumNumber:18,maximumNumber:60,}
},
experience : {
range : {minimumNumber:2,maximumNumber:20,conditionalExpression:'x => x.age >=25',}
},
salary : {
range : {minimumNumber:1000,maximumNumber:200000,message:'Your Salary should be between 10000 to 200000.',}
},
};
this.employeeInfoFormGroup = this.formBuilder.formGroup(employeeInfo,formBuilderConfiguration);
}
}

How to make tab key as enter key in Angular Material?

this is my angular materiel auto complete code
<input type="search" id="setId" name="setId" [attr.list]='collectionType' [(ngModel)]="selValue" class="text-box"
placeholder="--Select--" (focus)="ValidateParent()" (keyup.tab)="test()" (keyup)="EmitValues($event)" [id]="setId"
[matAutocomplete]="auto" [title]="selValue" [placeholder]='WaterMarkText'>
<div [hidden]="IsCascading">
<mat-autocomplete [id]="collectionType" #auto="matAutocomplete" (optionSelected)='onChange($event)'>
<mat-option *ngFor="let items of codeList" [value]="items.text" [attr.data-text]='items.text' [id]="items.value">
{{items.text}}
</mat-option>
</mat-autocomplete>
</div>
Angular material had a problem with tab selection.like the materiel auto complete not able to select the value while click the tab button. but it's working while click the enter button. So manually I need to overwrite the enter key event on tab key event. How could possible?
Improve my comment, and based on the response we can create a directive
import {
Directive,
AfterViewInit,
OnDestroy,
Optional
} from '#angular/core';
import {
MatAutocompleteTrigger
} from '#angular/material';
#Directive({
selector: '[tab-directive]'
})
export class TabDirective implements AfterViewInit, OnDestroy {
observable: any;
constructor(#Optional() private autoTrigger: MatAutocompleteTrigger) {}
ngAfterViewInit() {
this.observable = this.autoTrigger.panelClosingActions.subscribe(x => {
if (this.autoTrigger.activeOption) {
this.autoTrigger.writeValue(this.autoTrigger.activeOption.value)
}
})
}
ngOnDestroy() {
this.observable.unsubscribe();
}
}
You use:
<input tab-directive type="text" matInput [formControl]="myControl"
[matAutocomplete]="auto" >
(see stackblitz)
Update We can control only tab.key, else always you close, you get the selected value, so
#Directive({
selector: '[tab-directive]'
})
export class TabDirective {
observable: any;
constructor(#Optional() private autoTrigger: MatAutocompleteTrigger) {}
#HostListener('keydown.tab', ['$event.target']) onBlur() {
if (this.autoTrigger.activeOption) {
this.autoTrigger.writeValue(this.autoTrigger.activeOption.value)
}
}
}
(see a new stackblitz)
Update 2 I don't believe this answer has so many upvotes because it's wrong. As #Andrew allen comments, the directive not update the control. Well, It's late, but I try to solve. One Option is use
this.autoTrigger._onChange(this.autoTrigger.activeOption.value)
Anohter idea is inject the ngControl, so
constructor(#Optional() private autoTrigger: MatAutocompleteTrigger,
#Optional() private control: NgControl) {}
ngAfterViewInit() {
this.observable = this.autoTrigger.panelClosingActions.subscribe(x => {
if (this.autoTrigger.activeOption) {
const value = this.autoTrigger.activeOption.value;
if (this.control)
this.control.control.setValue(value, {
emit: false
});
this.autoTrigger.writeValue(value);
}
})
}
I'm a little late to the party; so there's one annoying issue with Eliseo's answer: It autocompletes even when the user has already selected a different option from the panel with a mouse click. The workaround I finally came up with was not straight forward at all.
/**
* Selects currently active item on TAB
* #example
* <input vxTabActiveOption [matAutocomplete]="matAutocomplate">
* <mat-autocomplete #matAutocomplate="matAutocomplete" autoActiveFirstOption>
*/
#Directive({ selector: '[vxTabActiveOption]' })
export class TabActiveOptionDirective implements AfterViewInit, OnDestroy {
private readonly destroy$ = new Subject<void>();
/**
* Whether or not the autocomplete panel was open before the event
*/
private panelOpen = false;
constructor(
private autoTrigger: MatAutocompleteTrigger,
private control: NgControl
) { }
ngAfterViewInit() {
const autocomplete = this.autoTrigger.autocomplete;
merge(
autocomplete.opened.pipe(map(() => true)),
autocomplete.closed.pipe(map(() => false))
).pipe(
takeUntil(this.destroy$),
delay(0)
).subscribe(value => this.panelOpen = value);
}
#HostListener('keydown.tab')
onBlur() {
if (this.panelOpen && this.autoTrigger.activeOption) {
const value = this.autoTrigger.activeOption.value;
this.control.control.setValue(value, { emit: false });
this.autoTrigger.writeValue(value);
}
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
Yes, I know it's an old question, but there're a better aproach that is use a directive like
#Directive({ selector: '[tab-selected]' })
export class TabSelected implements AfterViewInit {
constructor(private auto: MatAutocomplete) {}
ngAfterViewInit() {
this.auto._keyManager.onKeydown = (event: KeyboardEvent) => {
switch (event.keyCode) {
case TAB:
if (this.auto.isOpen) {
const option = this.auto.options.find(x => x.active);
if (option) {
option.select();
event.preventDefault();
return;
}
}
this.auto._keyManager.tabOut.next();
break;
case DOWN_ARROW:
this.auto._keyManager.setNextItemActive();
break;
case UP_ARROW:
this.auto._keyManager.setPreviousItemActive();
break;
}
};
}
}
You use like
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>Number</mat-label>
<input type="text"
placeholder="Pick one"
aria-label="Number"
matInput
[formControl]="myControl"
[matAutocomplete]="auto">
<mat-autocomplete tab-selected #auto="matAutocomplete"
autoActiveFirstOption >
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
You can be on work in this stackblitz

Kind of recursive usage of an Component possible?

After searching for like two hours for a solution I decided to ask some pros suspecting the solution could be quite simple.
It is an Angular7 project.
I would like to have a "goal" in my goals component with a button "+". When you click that button I want to have annother goal being added to the page. So I want to click a button of the goal component to create a new goal, which is something like recursive to me.
goals.component.html:
<input type="text" value="Ich brauche einen Laptop für maximal 1000 Euro.">
<br/>
<br/>
<app-goal id="{{lastGivenId+1}}"></app-goal>
goals.component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-goals',
templateUrl: './goals.component.html',
styleUrls: ['./goals.component.scss']
})
export class GoalsComponent implements OnInit {
lastGivenId: number = 0;
constructor() { }
ngOnInit() {
}
}
goal.component.ts and goal.component.html:
//Typescript code
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-goal',
templateUrl: './goal.component.html',
styleUrls: ['./goal.component.scss']
})
export class GoalComponent implements OnInit {
#Input() id : number;
constructor() { }
ngOnInit() {
}
onAddLowerGoal(currentGoalID:number){
// var goalElement = document.registerElement('app-goal');
// document.body.appendChild(new goalElement());
let newGoal = document.createElement("app-goal");
newGoal.setAttribute("id", "999");
let currentGoal = document.getElementById(currentGoalID.toString());
document.body.insertBefore(newGoal, currentGoal);
}
}
<html>
<div id="{{id}}" class="goal">goal{{id}}</div>
<button id="AddLowerGoal1" (click)="onAddLowerGoal(999)">+</button>
</html>
This way, it creates an app-goal element, but the div and button elements within the app-goal element is missing.
How can this problem be solved? Any help is welcome. Thanks in advance.
First glance: delete the html tags from your goal.component.html file.
Next: you can recursively add app-goal using angular. Inserting app-goal element the javascript way only adds the <app-goal></app-goal> object. It doesn't create an angular component. It doesn't bind your data.
Also if you're using Angular's #Input, you need to assign a component input with square braces. Do not use tags.
goals.component.html:
<input type="text" value="Ich brauche einen Laptop für maximal 1000 Euro.">
<br/>
<br/>
<app-goal [id]="lastGivenId+1"></app-goal>
goal.component.html:
<div id="{{id}}" class="goal">goal{{id}}</div>
<button id="AddLowerGoal1" (click)="onAddLowerGoal(999)">+</button>
<div *ngFor="let subGoal of subGoals">
<app-goal [id]="subGoal.id"></app-goal>
</div>
goal.component.ts:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-goal',
templateUrl: './goal.component.html',
styleUrls: ['./goal.component.scss']
})
export class GoalComponent implements OnInit {
#Input() id : number;
subGoals: Array<any> = [];
constructor() { }
ngOnInit() { }
onAddLowerGoal(currentGoalID: number){
this.subGoals.push({id: currentGoalID});
}
}
You can also use a service to store your goals and subgoals to access them later.
I think what you're looking for is a Reactive Form with FormArray with dynamically added form controls.
Take a look at this for eg:
import { Component } from '#angular/core';
import { FormControl, FormGroup, FormArray, FormBuilder } from '#angular/forms';
#Component({...})
export class GoalsComponent {
goalsForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.goalsForm = this.fb.group({
goals: this.fb.array([])
});
}
onFormSubmit() {
console.log('Form Value: ', this.goalsForm.value);
}
get goals() {
return (<FormArray>this.goalsForm.get('goals')).controls;
}
addGoal() {
(<FormArray>this.goalsForm.get('goals')).push(this.fb.control(null));
}
}
And here's the template for this:
<h2>Goals:</h2>
<form [formGroup]="goalsForm" (submit)="onFormSubmit()">
<button type="button" (click)="addGoal()">Add Goal</button>
<hr>
<div *ngFor="let goal of goals; let i = index;" formArrayName="goals">
<div>
<label for="goal">Goal {{ i + 1 }}: </label>
<input type="text" id="goal" [formControlName]="i">
</div>
<br>
</div>
<hr>
<button>Submit Form</button>
</form>
Here's a Sample StackBlitz for your ref.

Angular2: How do you pass a selected item from a HTML datalist element back to the component?

I have simple component which includes a to dreate a drop-down box. This is list is filled with the results from a Web API call. For display purposes I only use two fields of the item. However, once an element has been selected I need to do stuff with all the other fields. How do I pass the entire element back to the component?
Really would appreciate any help.
<h1>Get Locations</h1>
<div>
<div>
<input list="browsers" name="browser" #term (keyup)="search(term.value)">
<datalist id="browsers">
<option *ngFor="let item of items | async" >
{{item.code + " " + item.description}}
</option>
</datalist>
</div>
<input type="submit" value="Click" (click)="onSelect(item)" />
</div>
The component code is as follows:
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { LocationService } from './location.service';
import {Location} from './location.component';
import './rxjs-operators';
#Component({
selector: 'lesson-08',
templateUrl: './views/lesson08.html',
providers: [LocationService]
})
export class Lesson08 implements OnInit{
constructor(private locationService: LocationService) { }
aLoc: Location;
ngOnInit() {
this.aLoc = new Location();
}
errorMessage: string;
locations: Location[];
mode = 'Observable';
displayValue: string;
private searchTermStream = new Subject<string>();
search(term: string) {
this.searchTermStream.next(term);
}
onSelect(item: Location) {
// do stuff with this location
}
items: Observable<Location[]> = this.searchTermStream
.debounceTime(300)
.distinctUntilChanged()
.switchMap((term: string) => this.locationService.search(term));
}
The (click) event calling the method should be on the option selected. Your declared "item" is only known in the scope of the *ngFor, so on the levels of its children. You declared it on a too high level.