How to read JSON file in Angular cli? - json

I have an Angular cli project where I want to read data from a JSON file. These datas should be displayed on form's fields when the form is opened by user. What I have tried so far:
EmailSettingsComponent.ts
import { Component, OnInit, ViewChild, ViewEncapsulation, ChangeDetectorRef, Inject } from '#angular/core';
import * as FileSaver from 'file-saver';
import { MatDialog, MAT_DIALOG_DATA } from '#angular/material';
#Component({
selector: 'app-email-settings',
templateUrl: './email-settings.component.html',
styleUrls: ['./email-settings.component.css']
})
export class EmailSettingsComponent implements OnInit {
constructor() { }
smtpSettings: any;
saveJSON() {
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
// a.style = "display: none";
return function (data, fileName) {
//saving JSON code
};
}());
let smtpHost = (document.getElementById("smtpHost") as HTMLInputElement).value;
let smtpPort = (document.getElementById("smtpPort") as HTMLInputElement).value;
let smtpUserName = (document.getElementById("smtpUserName") as HTMLInputElement).value;
let smtpPassword = (document.getElementById("smtpPassword") as HTMLInputElement).value;
let smtpFrommtpHost = (document.getElementById("smtpFrom") as HTMLInputElement).value;
let smtpDisplayName = (document.getElementById("smtpDisplayName") as HTMLInputElement).value;
let smtpRecipients = (document.getElementById("smtpRecipients") as HTMLInputElement).value;
var data = { "Host": smtpHost, "Port": smtpPort, "UserName": smtpUserName, "UserPassword": smtpPassword, "From": smtpFrommtpHost, "DisplayName": smtpDisplayName, "Recipients":smtpRecipients, d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
}
ngOnInit(): void {
fetch('./assets/my-download.json').then(res => res.json())
.then(json => {
this.smtpSettings = json;
});
}
}
EmailSettingsComponent.html
<h1 mat-dialog-title>Email Settings</h1>
<div mat-dialog-content style="width: auto; height: auto">
<form id="formID" class="example-form" *ngFor="let item of smtpSettings">
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>SMTP Host</mat-label>
<textarea id="smtpHost" matInput placeholder="Ex: smtp.gmail.com">{{item.Host}}</textarea>
</mat-form-field>
<br />
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>SMTP Port</mat-label>
<textarea id="smtpPort" matInput placeholder="Ex: 587"></textarea>
</mat-form-field>
<br />
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>SMTP User Name</mat-label>
<textarea id="smtpUserName" matInput placeholder="Ex: example#gmail.com"></textarea>
</mat-form-field>
<br>
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>SMTP User Password</mat-label>
<textarea id="smtpPassword" matInput placeholder="Ex: password"></textarea>
</mat-form-field>
<br>
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>SMTP From</mat-label>
<textarea id="smtpFrom" matInput placeholder="Ex: example#gmail.com"></textarea>
</mat-form-field>
<br>
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>SMTP Display Name</mat-label>
<textarea id="smtpDisplayName" matInput placeholder="Ex: Jhon"></textarea>
</mat-form-field>
<br>
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>Recipients</mat-label>
<textarea id="smtpRecipients" matInput placeholder="Ex: someone#email.com; somebody#test.com"></textarea>
</mat-form-field>
<br>
<button mat-button (click)="saveJSON()">Save</button>
</form>
</div>
With the above code, I'm getting Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays..
Based on kva's reply on accepted answer of this post, I have replaced smtpSettings: any; with smtpSettings: any=[];. Following this action, I get rid of the above error, but I get another one which is Error trying to diff '[object Object]'. Only arrays and iterables are allowed.
How could I read the data from JSON and populate the form with it when the form is opened?

Related

how to add new event in calendar and apply drag and drop to it using angular cdk?

I am using NgxEventCalendarModule to create an event calendar to do the following task:
User can add a new event
user can edit the events
user can see the events
user can drag and drop event
here is my app.component.html
<div style="height: 100%; width: 100%;border: 1px solid gray;" >
<ngx-event-calendar
[showAddButton]="true"
[language]="'en'"
[dataSource]="dataArray"
(dayEvents)="selectDay($event)"
(newEvent)="addEvent($event)">
</ngx-event-calendar >
</div>
and app.component.ts
export class AppComponent {
title = 'de-calendar';
language: string = 'en';
dataArray: IEventData[] = testData;
constructor(public dialog: MatDialog) { }
addEvent(event) {
alert(event);
}
dayEvents(event) {
}
selectDay(event) {
if (event.events) {
const dialogRef = this.dialog.open(AddEventDialogComponent, {
width: '80%',
height: '90%',
data: event
});
}
}
IEventData.ts
export interface IEventData {
id: number;
title: string;
desc?: string;
startDate: Date;
endDate: Date;
createdBy?: string;
createdAt?: Date;
type?: number;
color?: string;
}
testData.ts
import { IEventData } from '../Interface/IEventData';
export const testData: IEventData[] = [
{ id: 20, title: 'Meeting with Manager', desc: 'Talk abut the new Task',
startDate: new Date("2022-12-22T21:00:00"), endDate: new Date("2022-12-26T23:00:00"), createdBy: 'Mark',
createdAt: new Date("2022-12-22T10:00:00"), type: 2, color: 'red' },
{ id: 12, title: 'Play Footbal', desc: 'Play FootBall wih freinds',
startDate: new Date("2022-12-19T13:43:00"), endDate: new Date("2022-12-23T15:00:00"), createdBy: 'Mark',
createdAt: new Date("2022-12-19T10:00:00"), type: 2, color: 'green' },
];
AddEventDialogComponent
export class AddEventDialogComponent implements OnInit {
startDate;
startHours;
startMinutes;
endDate;
endHours;
endMinutes;
hours:any;
minutes:any;
colours;
newEvent = {} as IEventData;
constructor(public dialogRef: MatDialogRef<EventDialogComponent>) { }
ngOnInit() {
this.hours = hours;
this.minutes = minutes;
this.colours = colours;
}
btn_SaveClick() {
this.startDate.setHours(this.startDate.getHours() + this.startHours)
this.startDate.setMinutes(this.startDate.getMinutes() + this.startMinutes)
this.endDate.setHours(this.endDate.getHours() + this.endHours)
this.endDate.setMinutes(this.endDate.getMinutes() + this.endMinutes);
this.newEvent.startDate = this.startDate;
this.newEvent.endDate = this.endDate;
this.dialogRef.close(AddEventDialogComponent);
}
AddEventDialogComponent.html
<h4>Add New Event</h4>
<mat-divider></mat-divider>
<div class="container">
<div class="first">
<mat-form-field class="date-picker">
<input readonly matInput [matDatepicker]="picker1" placeholder="Start date:" [(ngModel)]="startDate" (click)="picker1.open()">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker touchUi="true" #picker1></mat-datepicker>
</mat-form-field>
<mat-form-field class="date-picker">
<mat-label>Hours</mat-label>
<mat-select [(ngModel)]="startHours">
<mat-option *ngFor="let h of hours" [value]="h.id">{{ h.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="date-picker">
<mat-label>Minutes</mat-label>
<mat-select [(ngModel)]="startMinutes">
<mat-option *ngFor="let m of minutes" [value]="m.id">{{ m.minute }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="first">
<mat-form-field class="date-picker">
<input readonly matInput [matDatepicker]="picker2" placeholder="End date:" [(ngModel)]="endDate" (click)="picker2.open()">
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker touchUi="true" #picker2></mat-datepicker>
</mat-form-field>
<mat-form-field class="date-picker">
<mat-label>Hours</mat-label>
<mat-select [(ngModel)]="endHours">
<mat-option *ngFor="let h of hours" [value]="h.id">{{ h.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="date-picker">
<mat-label>Minutes</mat-label>
<mat-select [(ngModel)]="endMinutes">
<mat-option *ngFor="let m of minutes" [value]="m.id">{{ m.minute }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="second">
<mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
<input matInput placeholder="Title:" [(ngModel)]="newEvent.title">
</mat-form-field>
<mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
<input matInput placeholder="Description:" [(ngModel)]="newEvent.desc">
</mat-form-field>
<mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
<input matInput placeholder="Created By:" [(ngModel)]="newEvent.createdBy">
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Colours</mat-label>
<mat-select [(ngModel)]="newEvent.color">
<mat-option *ngFor="let color of colours" [value]="color.value">{{ color.name }}</mat-option>
</mat-select>
</mat-form-field>
<button mat-raised-button color="primary" (click)="btn_SaveClick()"
(keydown.enter)="btn_SaveClick()" [disabled]="!startDate || !startHours || !startMinutes || !endDate || !endHours ||
!endMinutes || !newEvent.title || (startDate > endDate) || (startDate >= endDate && startHours > endHours) ||
(startDate >= endDate && startHours >= endHours && startMinutes >= endMinutes)">SAVE</button>
</div>
</div>
the testData successfully works for me and shows the data on a calendar
but when I want to add a new event from the Interface it does not add the event!!!
here is the running app picture
can anyone help me how to add a new event from Interface and apply drag and drop to the event using angular CDK?????

Angular Material mat-stepper not working with 4 child items

I'm trying to create a mat-stepper on a new, empty page in Angular
it does work generally, but disappears when I add the 4th mat-from-field (in step 2)
the whole mat-stepper won't show up anymore after refreshing the page
input fields are all bound to a variable through "[(ngModel)]"
every mat-step has it's own "[stepControl]"
every form has it's own "[formGroup]"
HTML:
<mat-stepper linear labelPosition="bottom" #stepper>
<mat-step [stepControl]="firstFormGroup" [editable]="true">
<form [formGroup]="firstFormGroup" class="groupFields">
<ng-template matStepLabel>Fill out Project Info</ng-template>
<mat-form-field appearance="fill">
<mat-label>Project Name</mat-label>
<input matInput formControlName="firstCtrl" [(ngModel)]="projectName" required>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Requirements</mat-label>
<textarea [(ngModel)]="requirements"
matInput
cdkTextareaAutosize
#autosize="cdkTextareaAutosize"
cdkAutosizeMinRows="5"
cdkAutosizeMaxRows="15"></textarea>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Employee Email</mat-label>
<input matInput [(ngModel)]="email" required>
</mat-form-field>
<div>
<button mat-button matStepperNext>Next</button>
</div>
</form>
</mat-step>
<mat-step [stepControl]="secondFormGroup" [editable]="true">
<form [formGroup]="secondFormGroup">
<div class="customerFrom">
<div class="groupFields">
<ng-template matStepLabel>Fill out Customer Info</ng-template>
<mat-form-field appearance="fill">
<mat-label>Customer Name</mat-label>
<input matInput formControlName="secondCtrl" [(ngModel)]="company" required>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Address</mat-label>
<input [(ngModel)]="customerAddress" matInput>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>City</mat-label>
<input [(ngModel)]="customerCity" matInput>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Customer Type</mat-label>
<input [(ngModel)]="customerType" matInput>
</mat-form-field>
</div>
</div>
<div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button matStepperNext>Next</button>
</div>
</form>
</mat-step>
<mat-step [stepControl]="thirdFormGroup" [editable]="true">
<form [formGroup]="thirdFormGroup">
<div class="customerFrom">
<div class="groupFields">
<ng-template matStepLabel>Add Contacts</ng-template>
<mat-form-field appearance="fill">
<mat-label>Contact Stuff</mat-label>
<input formControlName="thirdCtrl" matInput>
</mat-form-field>
</div>
</div>
<div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button matStepperNext>Next</button>
</div>
</form>
</mat-step>
<mat-step>
<ng-template matStepLabel>Create Project</ng-template>
Create the Project or go back and edit!
<div>
<button mat-button matStepperPrevious>
<mat-icon>edit</mat-icon> back
</button>
<button mat-button (click)="createProject()">
<mat-icon>done</mat-icon> create Project
</button>
</div>
</mat-step>
</mat-stepper>
TS:
export class ProjectCreationComponent implements OnInit {
projectName: string = '';
selectedStatus: string = '';
requirements: string = '';
company: string = '';
customerAddress: string = '';
customerCity: string = '';
customerType: string = '';
forename: string = '';
surname: string = '';
address: string = '';
city: string = '';
email: string = '';
mobile: string = '';
contacts: Contact[] = [];
unsubscribe$: Subject<void> = new Subject<void>();
firstFormGroup = this._formBuilder.group({
firstCtrl: ['', Validators.required],
});
secondFormGroup = this._formBuilder.group({
secondCtrl: ['', Validators.required],
});
thirdFormGroup = this._formBuilder.group({
thirdCtrl: ['', Validators.required],
});
constructor(
private service: ProjectService,
private router: Router,
private _formBuilder: FormBuilder) { }
ngOnInit(): void {
}
addContact() {
let contact = {} as Contact;
contact.forename = this.forename;
contact.surname = this.surname;
contact.address = this.address;
contact.city = this.city;
contact.email = this.email;
contact.mobile = this.mobile;
this.contacts.push(contact);
}
deleteContact(contact: Contact) {
const index: number = this.contacts.indexOf(contact);
if(index !== -1) {
this.contacts.splice(index, 1);
}
}
createProject() {
const customer: Customer = {
name: this.company,
contacts: this.contacts,
address: this.customerAddress,
city: this.customerCity,
customerTyp: this.customerType
}
const announcement: Announcement = {
requirements: this.requirements,
customers: [customer],
offers: [],
}
const project: ProjectCreationRequest = {
name: this.projectName,
employeeEmail: this.email,
announcements: [announcement],
offers: []
};
this.service.createProject(project)
.pipe(takeUntil(this.unsubscribe$))
.subscribe();
this.router.navigateByUrl('/');
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
I've also exactly tried removing a mat-form-field (so that I only have 3 in the form), for every single one of them, so there is not a specific one that's causing the problem.
One more thing I've tried is changing "[(ngModel)]" to "[value]", because 2 way binding isn't necessarily needed, but with that the value of the textfield can't be stored in the variable.
Also I didn't find anything in the material documentation about a maximum size of step child items or anything.
Stackblitz (not 1:1 because of too many classes): https://stackblitz.com/edit/angular-buspzu?file=src/app/app.component.ts

angular (2021) formGroup expects a FormGroup instance. Please pass one in

i have problem with the formGroup in html
i just want to set the select with the service
hereĀ“s the html
<form [formGroup]="formGroup">
<div class="formInfo">
<mat-dialog-content>
<mat-form-field>
<mat-label>Titulo</mat-label>
<input matInput formControlName="tittle">
</mat-form-field>
<mat-form-field>
<mat-label>Modulo</mat-label>
<mat-select formControlName="idModule">
<mat-option *ngFor="let module of modules" value="{{module.idModule}}">{{module.name}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Opcion</mat-label>
<mat-select>
<mat-option value="one">First option</mat-option>
<mat-option value="two">Second option</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Tipo de Incidencia</mat-label>
<mat-select>
<mat-option value="one">First option</mat-option>
<mat-option value="two">Second option</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Fecha de Cierre</mat-label>
<input matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>Detalle Incidencia</mat-label>
<textarea matInput formControlName="incidentDetail"></textarea>
</mat-form-field>
<mat-form-field>
<mat-label>Comentario Cierre</mat-label>
<textarea matInput formControlName="closeComentary"></textarea>
</mat-form-field>
</mat-dialog-content>
</div>
</form>
.ts
import { Component, Inject, OnInit } from '#angular/core';
import { FormGroup, FormBuilder, FormControl, Validators } from '#angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '#angular/material/dialog';
import { fadeInFadeOut } from '#app/share/animations/fadeInFadeOut';
import { GetModulesModel } from '../models/ticket.model';
import { TicketFormConstant } from '../models/ticket-form-constant';
#Component({
selector: 'app-incident-registration-form-dialog',
templateUrl: './incident-registration-form-dialog.component.html',
styleUrls: ['./incident-registration-form-dialog.component.sass'],
animations: [fadeInFadeOut]
})
export class IncidentRegistrationFormDialogComponent implements OnInit {
formGroup: FormGroup;
element: any;
isDisabled: boolean;
constructor(private fb: FormBuilder,
public dialogRef: MatDialogRef<IncidentRegistrationFormDialogComponent>, #Inject(MAT_DIALOG_DATA) private data) {
}
modulesOptions = TicketFormConstant.URL_PATH_TICKET_MODULE;
selectModule: GetModulesModel[] = JSON.parse(localStorage.getItem('modules'));
ngOnInit(): void {
this.element = this.data.element;
this.isDisabled = this.data.isDisabled;
this.formGroup = this.fb.group({
tittle : new FormControl(),
idModule : new FormControl({ value: this.data.element.idModule ? this.data.element.idModule.toString() : '', disabled: this.isDisabled}, [Validators.required]),
options : new FormControl(),
incidentType: new FormControl(),
closeDate : new FormControl(),
incidentDetail: new FormControl(),
closeComentary: new FormControl(),
});
}
}

register an angular form in a nested json

I am trying to convert a html form to a nested json.
These are my classes :
export class Config {
id: string;
name: string;
email: string;
lchart:ComponentLinechart;
}
export class ComponentLinechart {
name_linechart : String;
xAxis_linechart : String;
yAxis_linechart : String;
}
The formcomponent.ts:-
export class FormsComponent implements OnInit {
newConfig: Config = new Config();
constructor(private service : MyserviceService, private configservice:ConfigurationService) {
}
email = new FormControl('', [Validators.required, Validators.email]);
xAxisControl = new FormControl('', Validators.required);
yAxisControl = new FormControl('', Validators.required);
name_linechart = new FormControl('', Validators.required);
name = new FormControl('', Validators.required);
getConfig(): void {
this.configservice.getConfig()
.subscribe(data => this.configs = data );
}
createConfiguration(todoForm: NgForm): void {
this.configservice.createConfig(this.newConfig)
.subscribe(createconfig => {
todoForm.reset();
this.newConfig = new Config();
this.configs.unshift(createconfig)
});
}
The formcomponent.html :-
<form #todoForm="ngForm" (ngSubmit)="createConfiguration(todoForm)" novalidate>
<div class="example-container">
<mat-form-field appearance="fill">
<mat-label>Enter your name</mat-label>
<input matInput [(ngModel)]="newConfig.name" name="name" [formControl]="name" required>
</mat-form-field>
<br>
<mat-form-field appearance="fill">
<mat-label>Enter your email</mat-label>
<input matInput placeholder="pat#example.com" [(ngModel)]="newConfig.email" name="email"
[formControl]="email" required>
<mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>
<br>
<mat-form-field appearance="fill">
<mat-label>Name-linechart</mat-label>
<input matInput [(ngModel)]="newConfig.name_linechart" name="name_linechart"
[formControl]="name_linechart" required>
</mat-form-field>
<br>
<mat-form-field *ngIf = "sales" >
<mat-label>xAxis-linechart</mat-label>
<mat-select [(ngModel)]="newConfig.xAxis-linechart" name="xAxis-linechart"
[formControl]="xAxisControl" required>
<mat-option *ngFor="let field of fields" [value] = "field">
{{field}}
</mat-option>
</mat-select>
<mat-error *ngIf="xAxisControl.hasError('required')">Please choose a field</mat-error>
</mat-form-field>
<br>
<mat-form-field *ngIf = "sales" >
<mat-label>yAxis-linechart</mat-label>
<mat-select [(ngModel)]="newConfig.yAxis-linechart" name="yAxis-linechart"
[formControl]="yAxisControl" required>
<mat-option *ngFor="let field of fields" [value] = "field">
{{field}}
</mat-option>
</mat-select>
<mat-error *ngIf="yAxisControl.hasError('required')">Please choose a field</mat-error>
</mat-form-field>
Expected result :
{
"name": "adam",
"email": "adam#gmail.com",
"lchart": {
"name_linechart": "books",
"xAxis_linechart": "library",
"yAxis_linechart": "percentage"
}
}
But this is what I get :
{
"name": "adam",
"email": "adam#gmail.com",
"lchart": null
}
I tried to write newConfig.lchart.name_linechart in the formcomponent.html but it gives me the error :
TypeError : cannot read property name_linechart of undefined.
Foufa, NEVER, NEVER, NEVER, NEVER use [(ngModel)] and formControlName (or formControl) in the same tag. One is for template Form, another for ReactiveForms, see the docs
Well. You has an object that has properties, one of them is an object, so, you has a FormGroup with somes FormControls and one FormGroup, (again the docs)
myForm=new FormGroup({
name:new FormControl(),
email:new FormControl(),
lchart:new FormGroup({
name_linechart: new FormControl(),
xAxis_linechart: new FormControl(),
yAxis_linechart: new FormControl(),
})
})
And the .html
<form [formGroup]="myForm">
<!--see, under the formGroup, we using formControlName for the formControl-->
<input formControlName="name">
<input formControlName="email">
<!--when we has a FomgGroup, we use formGrpupName in a div-->
<div formGroupName="lchart">
<!--and formControlName under the div -->
<input formControlName="name_linechart">
<input formControlName="xAxis_linechart">
<input formControlName="yAxis_linechart">
</div>
</form>
<!--we can add, only for check-->
<pre>
{{myForm?.value|json}}
</pre>
Update as always, is util use a function that received an object and create the form
getForm(data:any)
{
data=data || { name:null,
email:null,
lchart:{
name_linechart:null,
xAxis_linechart:null,
yAxis_linechart:0
}
}
return new FormGroup({
name:new FormControl(data.name,Validator.required),
email:new FormControl(data.email,[Validator.required,Validators.emailValidator),
lchart:new FormGroup({
name_linechart: new FormControl(data.lchart.name_linechart),
xAxis_linechart: new FormControl(data.lchart.xAxis_linechart),
yAxis_linechart: new FormControl(data.lchart.yAxis_linechart),
})
}
And use as
myForm=this.getForm(data) //<--if we has an object "data"
//or
myForm=this.getForm(null) //if we want a empty form
I guess your [(ngModel)] binding wrong for name_linechart,xAxis_linechart,yAxis_linechart fields.
It should be
[(ngModel)]="newConfig.lchart.name_linechart"
[(ngModel)]="newConfig.lchart.xAxis_linechart"
[(ngModel)]="newConfig.lchart.yAxis_linechart"
change your constructor to-
constructor(private service : MyserviceService, private configservice:ConfigurationService) {
this.newConfig.lchart=new ComponentLinechart(); //add this line
}

Filter autocomplete Material. Some input form work like one input

can you help me please. I have some problem with Autocomplete Material.
I don't know what is the problem, I follow this tutorial: https://material.angular.io/components/autocomplete/overview
In component.ts
import { Component } from '#angular/core';
import { FormControl } from '#angular/forms';
import { Observable } from 'rxjs/Observable';
import { startWith } from 'rxjs/operators/startWith';
import { map } from 'rxjs/operators/map';
#Component({ selector: 'autocomplete-filter-example',
templateUrl: 'autocomplete-filter-example.html',
styleUrls: ['autocomplete-filter-example.css'] })
export class AutocompleteFilterExample {
myControl: FormControl = new FormControl();
myControl1: FormControl = new FormControl();
myControl2: FormControl = new FormControl();
options = [
'One',
'Two',
'Three' ];
options1 = [
'test',
'test2',
'test1' ];
options2 = [
'test3',
'test5',
'test10' ];
filteredOptions: Observable<string[]>;
filteredOptions1: Observable<string[]>;
filteredOptions2: Observable<string[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(val => this.filter(val))
);
this.filteredOptions1 = this.myControl1.valueChanges
.pipe(
startWith(''),
map(val => this.filter1(val))
);
this.filteredOptions1 = this.myControl1.valueChanges
.pipe(
startWith(''),
map(val => this.filter1(val))
);
this.filteredOptions2 = this.myControl2.valueChanges
.pipe(
startWith(''),
map(val => this.filter2(val))
); }
filter(val: string): string[] {
return this.options.filter(option =>
option.toLowerCase().indexOf(val.toLowerCase()) === 0); }
filter1(value: string): string[] {
return this.options1.filter(option1 =>
option1.toLowerCase().indexOf(value.toLowerCase()) === 0); }
filter2(value: string): string[] {
return this.options1.filter(option1 =>
option1.toLowerCase().indexOf(value.toLowerCase()) === 0); }
}
Component.html
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one1" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one2" aria-label="Number" matInput [formControl]="myControl1" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option1 of filteredOptions1 | async" [value]="option1">
{{ option1 }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one3" aria-label="Number" matInput [formControl]="myControl2" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option2 of filteredOptions2 | async" [value]="option2">
{{ option2 }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
My question is: Why input work like one and display only one array? In this link you can see my problem.
https://stackblitz.com/edit/angular-yw23zr-u25rqk?file=app%2Fautocomplete-filter-example.html
Please if have some idea, I want to help me. Thank you
You need to have different template reference for your different autocomplete.
your need <mat-autocomplete #auto="matAutocomplete"> / <mat-autocomplete #auto1="matAutocomplete"> and <mat-autocomplete #auto2="matAutocomplete">
and [matAutocomplete]="auto" [matAutocomplete]="auto1" [matAutocomplete]="auto2"
In your example, you use the reference #auto multiple times, so it keeps the last autocomplete as reference ( that why you see the same list three times).
Plus you have some typo in your example :
1/ your have this block twice
this.filteredOptions1 = this.myControl1.valueChanges
.pipe(
startWith(''),
map(val => this.filter1(val))
);
2/ your filter2 value is based upon this.value1 for filtering instead of this.option2
Here is the forked stackblitz