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

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

Related

How to create Angular Material Chips unique to each expansion panel?

My goal is to create Angular Material Chips that are unique to each expansion panel. For example, panel 1 should have chips called chip 1 and chip 2, while panel 2 should have chip 3 and chip 4. However, the panels should all show up on a singular page (such as localhost:4200).
When I run my current code, it produces chips that appear on every panel, and when a chip is deleted, it is deleted from every panel as well. I believe that the solution lies in creating an *ngFor loop with tags being replaced with p.tags, where adding a tag will be unique to that object’s tags array. However, I can’t figure out how push that data back into a singular object and then display that data on my html page.
Here's what the .ts code looks like.
import { Component, OnInit } from "#angular/core";
import { MatChipInputEvent } from "#angular/material/chips";
import { COMMA, ENTER } from "#angular/cdk/keycodes";
export interface People {
people: Person[];
}
export interface Person {
name: string;
id: string;
tags: string[];
}
#Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class PersonComponent implements OnInit {
persons;
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
tags: string[] = [];
constructor(private personService: PersonService) {}
ngOnInit() {
this.personService
.getStudents()
.subscribe((data) => (this.persons = data.persons));
}
add(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
if ((value || "").trim()) {
this.tags.push(value.trim());
}
if (input) {
input.value = "";
}
}
remove(tag: string): void {
const index = this.tags.indexOf(tag);
if (index >= 0) {
this.tags.splice(index, 1);
}
}
}
Here's what the .html code looks like.
<mat-expansion-panel *ngFor="let p of persons>
<mat-expansion-panel-header [collapsedHeight]="'125px'" [expandedHeight]="'125px'">
{{ p.name }}
</mat-expansion-panel-header>
<mat-form-field>
<mat-chip-list #chipList>
<!-- tags should be switched to p.tags here I think -->
<mat-chip *ngFor="let tag of tags" [selectable]="selectable"
[removable]="removable" (removed)="remove(tag)">
{{tag}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input placeholder="Add a tag"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
</mat-form-field>
</mat-expansion-panel>

how to hide items from switch statement in angular

I'm learning Angular and wondering how I can't hide some item and show certain items only when the user select specific item in the drop down list.
For example, In my page, I have Chart TextBox, Text TextBox, Grid TextBox and a drop down list that contain Chart, Text, and Grid. when ever user select Text, I want to show only Text TextBox and hide the rest.
right now, the three chart type options are showing on drop drop list when ever I run the project but it's not doing anything when I select Text and also I got an error on my ngIf saying that
"Property 'text' does not exist on type 'ChartType'."
I would be really appreciate if can somebody teach me or help me.
The problem I have is in the project I found from from github, the data for drop down list is in the another file called chart.model.ts and it written like this
export class ChartUtil {
public static getChartTypeDisplay(type: ChartType): string {
switch (type) {
case ChartType.chart:
return "Chart"
case ChartType.text:
return "Text";
case ChartType.grid:
return "Grid";
default:
return "unknown";
}
}
}
and display it like this
design.component.ts
chartTypes: TypeListItem[] = [];
setupTypes() {
let keys = Object.keys(ChartType);
for (let i = 0; i < (keys.length / 2); i++) {
this.chartTypes.push({ value: parseInt(keys[i]), display: ChartUtil.getChartTypeDisplay(parseInt(keys[i])) })
}
html
<ng-container *ngIf="chart.chartTypes == chartTypes.text">
<mat-form-field appearance="fill">
<mat-label>Text</mat-label>
<input matInput />
</mat-form-field>
I can't uploaded the full project on stackblitz but I uploaded all the code from those file over https://stackblitz.com/edit/angular-ivy-dmf3vn
This is normally how you would tackle a ng-switch
Component Code (badly done)
import { Component, VERSION, OnInit } from '#angular/core';
export class ChartType {
chart = 1;
text = 2;
grid = 3;
}
export class TypeListItem {
public value = 0;
public display = '';
public chartType = -1;
}
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
public chartTypesEnum = new ChartType();
public chartTypes: TypeListItem[] = [];
ngOnInit() {
let keys = Object.keys(this.chartTypesEnum);
for (let i = 0; i < (keys.length ); i++) {
this.chartTypes.push(
{
value: parseInt(ChartType[keys[i]]),
chartType: this.chartTypesEnum[keys[i]],
display: `This is a ${keys[i]}`
})
}
}
}
HTML (again badly done but simple)
<ng-container *ngFor="let chart of chartTypes">
<ng-container [ngSwitch]="chart.chartType" >
<div *ngSwitchCase="chartTypesEnum.chart">Chart</div>
<div *ngSwitchCase="chartTypesEnum.grid">Grid</div>
<div *ngSwitchCase="chartTypesEnum.text">Text</div>
</ng-container>
</ng-container>
Example
https://stackblitz.com/edit/angular-ivy-bievwr
Example 2
https://stackblitz.com/edit/angular-ivy-jhv4bq
This solution will render an Angular Material dropdown List using Enum with the ChartTypes insted of the your switch.
The Component:
import { Component, OnInit } from '#angular/core';
export enum ChartTypes {
Chart = 'Chart',
Text = 'Text',
Grid = 'Grid',
}
#Component({
selector: 'app-select-by-type',
templateUrl: './select-by-type.component.html',
styleUrls: ['./select-by-type.component.css']
})
export class SelectByTypeComponent implements OnInit {
// create an enum variable to work with on the view
chartTypes = ChartTypes;
// initialize the dropdown to a default value (in this case it's Chart)
chartsValue: string = ChartTypes.Chart;
constructor() { }
ngOnInit() {
}
}
The View:
<mat-form-field appearance="fill">
<mat-select required [(value)]="chartsValue">
<mat-option *ngFor="let chartType of chartTypes | keyvalue" [value]="chartType.value">{{chartType.value}}
</mat-option>
</mat-select>
<mat-label>Chart Type</mat-label>
</mat-form-field>
<ng-container *ngIf="chartsValue === chartTypes.Text">
<mat-form-field appearance="fill">
<mat-label>Text</mat-label>
<input matInput />
</mat-form-field>
</ng-container>
<ng-container *ngIf="chartsValue === chartTypes.Chart">
Chart In Template
</ng-container>
<ng-container *ngIf="chartsValue === chartTypes.Grid">
Grid In Template
</ng-container>

focus for ng-select not working Angular 5

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();
}

Angular 6 show dropdown dependent selected option

I have two dropdown select option, but I'm struggling update second's selected option based on first one.
HTML
<form novalidate [formGroup]="editModuleForm" (ngSubmit)="onSubmitForm()">
<div align="center">
<mat-form-field>
<mat-select placeholder="Select Module" formControlName="moduleControl" required>
<mat-option *ngFor="let module of modules" [value]="module" (click)="popData()">
{{ module.title }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
<div *ngIf="editModuleForm.get('moduleControl').value" align="center">
<div align="center">
<mat-form-field>
<mat-select placeholder="Select Course" formControlName="courseControl">
<mat-option *ngFor="let course of courses" [value]="course.courseId" >
{{ course.name }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</div>
Component
constructor(private putService: PutService, private getService: GetService,
private router: Router, private formBuilder: FormBuilder) {}
ngOnInit() {
this.getService.findAllModule().subscribe(modules => {
this.modules = modules;
});
this.getService.findAllCourses().subscribe(courses => {
this.courses = courses;
});
this.editModuleForm = this.formBuilder.group({
moduleControl: this.formBuilder.control(null),
courseControl: this.formBuilder.control(null)
});}
popData() {
this.editModuleForm.get('moduleControl').valueChanges.subscribe(
value => {
this.editModuleForm.controls['courseControl'].setValue(value.course);
console.log(value);
}
);}
After selecting an item in the first dropdown, I would like to default select module's course in the second dropdown and refresh after selecting another one.
You need subscribe changes on ngOnInit() no need to call click event
here's an example
ngOnInit() {
this.editModuleForm = this.formBuilder.group({
moduleControl: '',
courseControl: ''
});
this.popData();
}
popData() {
this.editModuleForm.controls['moduleControl'].valueChanges.subscribe(
value => {
this.editModuleForm.controls['courseControl'].setValue(value.id);
}
);
}
Stackblitz demo
I think the problem is you are calling this.editModuleForm.get('moduleControl').valueChanges in the click event, you actually want to call that in the ngOnInit. Its starting to listen to the value changes are the value has already changed!
Maybe try this:
constructor(private putService: PutService, private getService: GetService,
private router: Router, private formBuilder: FormBuilder) {}
ngOnInit() {
this.getService.findAllModule().subscribe(modules => {
this.modules = modules;
});
this.getService.findAllCourses().subscribe(courses => {
this.courses = courses;
});
this.editModuleForm = this.formBuilder.group({
moduleControl: this.formBuilder.control(null),
courseControl: this.formBuilder.control(null)
});
this.editModuleForm.get('moduleControl').valueChanges.subscribe(
value => {
this.editModuleForm.controls['courseControl'].setValue(value.course);
console.log(value);
}
}
You can get rid of the click event and the pop() method

Angular 2 dialog popup with text field input

I have a simple popup that shows a message with OK button to release it, what I want is to add to this popup a text field that the user will need to type something in it and click OK to submit his answer.
currently it looks like this:
#Component({
selector: 'dialog-component',
template: `<h2>{{title}}</h2>
<p>{{message}}</p>
<button md-button (click)="dialog.close()">OK</button>`
})
export class DialogComponent {
public title: string;
public message: string;
constructor( public dialog: MdDialogRef<DialogComponent>) { }
}
and im using it like:
public showDialog(message: MessageBoxMessage) {
if (typeof message !== 'undefined') {
let dialogRef: MdDialogRef<DialogComponent> = this._dialog.open(DialogComponent);
dialogRef.componentInstance.title = message.title;
dialogRef.componentInstance.message = message.content;
}
}
how can I change it to have a popup with text-field and ok button tht pass me the value of the text-field?
You can create EventEmitter in your dialog:
#Component({
selector: 'dialog-component',
template: `<h2>{{title}}</h2>
<p>{{message}}</p>
<mat-form-field class="example-full-width">
<input matInput placeholder="Favorite food" #input>
</mat-form-field>
<button mat-button (click)="onOk.emit(input.value); dialog.close()">OK</button>`
})
export class DialogComponent {
public title: string;
public message: string;
onOk = new EventEmitter();
constructor( public dialog: MatDialogRef<ErrorDialogComponent>) { }
}
then subscribe to it in parent component
dialogRef.componentInstance.onOk.subscribe(result => {
this.resultFromDialog = result;
})
Plunker Example
Another way is passing value to MatDialog.close method
(click)="dialog.close(input.value)"
....
dialogRef.afterClosed().subscribe(result => {
this.resultFromDialog = result;
});
Plunker Example
You can bind the answer to a model like this :
#Component({
selector: 'dialog-component',
template: `<h2>{{title}}</h2>
<p>{{message}}</p>
<input type="text" name="data" [(ngModel)]="data">
<button md-button (click)="dialog.close()">OK</button>`
})
export class DialogComponent {
public title: string;
public message: string;
data: string;
constructor( public dialog: MdDialogRef<ErrorDialogComponent>) { }
}
And then bind the (click) to a function that sends your data.