reactive form control with json as default value - html

Hi I am facing an issue with reactive form control usage. For mat-select I have a default JSON array with name and id. Of which I am showing only name in the drop down. I want to set a name as default using similar JSON but I am not able to do that. Kindly suggest:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
form: FormGroup
data: any
constructor(
private formBuilder: FormBuilder
) {}
ngOnInit() {
this.stateList = [{
name: 'def',
id: '1'
}, {
name: 'ghi',
id: '2'
}];
this.form = this.formBuilder.group({
state: {
name: 'abc',
id: '1'
}
})
}
}
<form [formGroup]="form">
<mat-form-field>
<mat-label>Color</mat-label>
<mat-select [(value)]="state.name" formControlName="state">
<mat-option *ngFor="let state of stateList" [value]="state">
{{ state.name }}</mat-option>
</mat-select>
</mat-form-field>
</form>

Related

Refresh Angular-Component after Radio Button Selection

I am trying to refresh a component (in html via ) that includes mat-cards after changing the value of a mat radio button group. Somehow I cant get the change-event and the following redirection to work:
app.component.html:
<mat-radio-group
aria-labelledby="example-radio-group-label"
class="example-radio-group"
[(ngModel)]="Sprache"
(change)="radioChange($event)">
<mat-radio-button class="example-radio-button" *ngFor="let season of sprachen" [value]="season">
{{season}}
</mat-radio-button>
</mat-radio-group>
app.component.ts:
import { Component} from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Juliens MEAN-Pokedex';
showFiller = false;
Sprache: string;
sprachen: string[] = ['de', 'en', 'fr', 'ja', 'kr', 'zh'];
constructor(private router: Router){
}
radioChange(e){
this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate(['Dashboard']));
}
}

Angular DropDown - Unable to display value on View

In my component I have 2 Strings that I need to display on Angular Form as Dropdown, I am struggling to get the values on HTML page
Demo - https://stackblitz.com/edit/angular-dc4s7d?file=src%2Fapp%2Fapp.component.ts
Here is my ts code
export class EmployeeComponent implements OnInit {
constructor(public employeeService: EmployeeService) {}
public listItem: string[];
ngOnInit() {
this.listItem = ["A", "B"]; ----->>>>> Dropdown values
}
Html code
<div class="m-3 input-group; padding:10px; color:red; border: 3px solid ">
<span class="input-group-text">Type</span>
<select type="text" name="type" #type="ngModel"
[(ngModel)]="employeeService.selectedEmployee.type "placeholder="Type">
<option *ngFor="let dl of listItem" [value]="dl">{{dl}}</option>
</select>
</div>
Something may be wrong with your code but I can provide you a sample code to bind data with dropdown list. Please check and let me know.
HTML
<select name="city" (change)="onChange($event.target.value)">
<option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
</select>
TS:
countries = [{
id: 1, name: 'France', cities: ['Paris', 'Marseille', 'Nice']
},
{
id: 2, name: 'Germany', cities: ['Hamburg', 'Berlin', 'Munich']
},
{
id: 3, name: 'Italy', cities: ['Roma', 'Milan', 'Napoli']
},
];
onChange(deviceValue) {
//do something
}
Note: Please Check the link of Stackblitz for more information LINK
NEW UPDATE
I think employeeService.selectedEmployee is not available on that link. That's the reason why your code was not working and You have to make a little change in listitem. Finally, code will look like =>
TS:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
selectedtype: any;
listItems= [{ name: 'A'},{ name: 'B'}];
ngOnInit() {
}
onChange(deviceValue) {
}
}
HTML:
<select name="dt" (change)="onChange($event.target.value)"
[(ngModel)]="selectedtype" placeholder="Type"
#type="ngModel" type="text">
<option *ngFor="let data of listItems" [value]="data.name">{{data.name}}</option>
</select>
NOTE: Provide link contain 4 errors.
Try Using :
You need to initialize your selectedEmployee in you service file
#Injectable({
providedIn: "root"
})
export class EmployeeService {
public selectedEmployee: Employee = {
_id: '',
name: '',
date: null,
designation: '',
salary: null,
type: null
};
constructor() {}
}
Check in your stackblitz demo path.
I think this will help you...

Setting selected in dropdownlist with Angular

I have a list displayed in a dropdownlist, but it displays the default as a blank and not as the first item in the dropdown.
I have tried adding let i = 0 and then [selected]="i = 0", but this does not seem to set the default item to the first item, however I am receiving the correct value back from i.
Below is my code:
<div class="form-group">
<label for="userName">User Name</label>
<select formControlName="userName" class="form-control" (change)="userChange($event)">
<option *ngFor="let row of usersModel;let i = index" value="{{ row.id }}" [selected]="i == 0">{{ row.userName }} {{ i }}</option>
</select>
</div>
Here is my TypeScript File:
import { Component, OnInit } from '#angular/core';
import { UserAdminService } from '../../services/user-admin.service';
import { FormBuilder, Form, FormControl, FormGroup } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'lib-add-user-to-role',
templateUrl: './add-user-to-role.component.html',
styleUrls: ['./add-user-to-role.component.css']
})
export class AddUserToRoleComponent implements OnInit {
addUserToRoleForm: FormGroup;
rolesModel: any[];
usersModel: any[];
selectedRole: string;
selectedUser: string;
constructor(private userAdminService: UserAdminService, private formBuilder: FormBuilder, private router: Router) {
var roleControl = new FormControl('');
var userControl = new FormControl('');
this.addUserToRoleForm = formBuilder.group({ roleName: roleControl, userName: userControl });
}
ngOnInit() {
this.userAdminService.getRoles().subscribe(roles => {
this.rolesModel = roles;
this.selectedRole = this.rolesModel[0].name;
this.userAdminService.getUsersNotInRole(this.selectedRole).subscribe(users => {
this.usersModel = users;
this.selectedUser = this.usersModel[0].id;
console.log(this.usersModel[0].userName);
this.addUserToRoleForm.controls['roleName'].setValue(this.rolesModel[0].name);
this.addUserToRoleForm.controls['userName'].setValue(this.usersModel[0].userName);
});
});
}
userChange(event: any) {
this.selectedUser = event.target.value;
console.log('Selected ' + this.selectedUser);
}
AddUserToRole() {
this.userAdminService.addUserToRole(this.selectedUser, this.selectedRole)
.subscribe(result => {
if (result.success) {
this.router.navigate(['/roleusermaint']);
}
else {
console.log('Error Received on adding user to role');
}
});
}
}
As you can see I added {{ i }} in the text to make sure it shows the value of i and it does:
What am I missing ?
Thanks for any help!
#Axle, if you're using a Reactive Form, you needn't use [selected] nor (change), just, when you create the form you give value to userName
Using the constructor
const firstId=usersModel[0].id
this.form=new FormGroup({
userName:new FormControl(firstId)
})
Using formBuilder
const firstId=usersModel[0].id
this.form=this.fb.group({
userName:firstId
})
Using setValue, after create the form
const firstId=usersModel[0].id
this.form.get('userName').setValue(firstId)
As you are using Angular reactive form, try to keep the logic in ts file itself.
Using setValue(), you can set the default value to a control.
To set the default value to form control you could to it like,
this.form.controls['country'].setValue(this.countries[0].id)
In template use it like,
<option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</option>
Working Stackblitz
Ref:
A complete sample code would be something like,
app.component.ts
import { Component } from '#angular/core';
import { FormGroup, FormControl } from '#angular/forms';
import {Country} from './country';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
countries = [
{
id: 'us',
name: 'United States'
},
{
id: 'uk',
name: 'United Kingdom'
},
{
id: 'ca',
name: 'Canada'
}
];
form: FormGroup;
ngOnInit(){
this.form = new FormGroup({
country: new FormControl('')
});
this.form.controls['country'].setValue(this.countries[0].id)
}
}
app.component.html
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</option>
</select>
</form>

How to get selected value of dropdown in angular 6 on load(not onchange)

I have a select dropdown ,I am getting option's data and value from an array through loop. Here I need to get the value of selected drop down when page loads without onchange(in this case Recent). Here is code below.
app.component.html
<select>
<option *ngFor="let v of values" [value]="v.id">
{{v.name}}
</option>
</select>
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'projectchart';
public values = [
{ id: 3432, name: "Recent" },
{ id: 3442, name: "Most Popular" },
{ id: 3352, name: "Rating" }
];
ngOnInit(){
alert('The default selected value is');
}
}
you could make use of reactive forms
constructor(private fb: FormBuilder) { }
// create a form group using the form builder service
formName = this.fb.group({
name: ['']
})
in the template
<form [formGroup]="formName">
<select formControlName="name">
<option *ngFor="let v of values" [value]="v.id">
{{v.name}}
</option>
</select>
</>
and then get the value in the ts:
this.formName.controls['name'].value

FormControl is not provided by any applicable directives

FormControl is having difficulties with directives...
I am trying to implement an autocomplete into my input field. I am using the following angular-material guide to the point that I have verbatim copy and pasted their typescript and html to test it out: https://material.angular.io/components/autocomplete/overview.
I keep receiving an error on FormControl in the HTML that reads: "Property FormControl is not provided by any applicable directives nor by input element. Inspection info: Reports undefined property, event or structural directive bindings on elements."
HTML CODE:
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" 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>
</form>
TS CODE:
import {Component, OnInit} from '#angular/core';
import {FormControl} from '#angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
#Component({
selector: 'mySelector',
templateUrl: 'myTemplate.html',
styleUrls: ['myCSS.css'],
})
export class myExportClass implements OnInit {
myControl = new FormControl();
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option =>
option.toLowerCase().includes(filterValue));
}
}
As stated in the docs: "For this example, be sure to import ReactiveFormsModule from #angular/forms into your NgModule"
So ensure that your app.module contains the module e.g.:
import {FormsModule, ReactiveFormsModule} from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent,
],
imports: [
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }