Default selected checkbox - html

I want to ask about how I can set option to be default selected?
<form [formGroup]="form2">
<select formControlName="drop">
<option disabled>Choose one</option>
<option *ngFor="let example of examples" [value]="example.id" [disabled]="example.isDisabled" [selected]="example.isSelected">{{ example.name }}</option>
</select>
</form>
Component:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
#Component({
selector: 'app-drop-down-list',
templateUrl: './drop-down-list.component.html',
styleUrls: ['./drop-down-list.component.css']
})
export class DropDownListComponent implements OnInit {
public form = new FormGroup({
drop: new FormControl('',
Validators.required,
),
});
public form2 = new FormGroup({
drop: new FormControl('',
Validators.required,
),
});
examples = [{
id: 1, name: 'Test1', isSelected: false, isDisabled: true,
},
{
id: 2, name: 'Test2', isSelected: true, isDisabled: false,
},
{
id: 3, name: 'Test3', isDisabled: false,
}
];
constructor() { }
ngOnInit() {
}
onSubmit(form) {
console.log(form);
}
}
I was searching on stack but I don't want to mix reactive forms with ngModel, also I don't wan't to use patchValue because It only set default value without choosing element in list. Thanks for help!

if you want option to be selected then do like this , just pass id value in your formcontrol intialization
public form2 = new FormGroup({
drop: new FormControl(this.examples[0].id,
Validators.required,
),
});
or if you dont want to initialization immediately and want later on then make use of setValue method, below is required when you are fecthing data from server and want to set value i just hard coded value just to show as example , you should replace with the value you get from server
form2.get('drop').setValue('1');
html should be as below no need of [selected]
<select formControlName="drop">
<option disabled>Choose one</option>
<option *ngFor="let example of examples" [value]="example.id" [disabled]="example.isDisabled" >{{ example.name }}</option>
</select>

Related

Angular CLI disable html form if previous option not selected?

I have a form that has a few select fields populated with options.
<form [formGroup]="selectVehicleForm">
<select formControlName="Manufacturer">
<option *ngFor='let cars of cars$'>{{cars.Manufacturer}}</option>
</select>
<select formControlName="Model">
<option *ngFor='let cars of cars$'>{{cars.Model}}</option>
</select>
</form>
My question - how can I disable my "Model" field as long as a user has nothing selected in "Manufacturer"?
You can try like this (not tested) :
constructor(private fb: FormBuilder) {
this.selectVehicleForm = this.fb.group({
Manufacturer: [],
Model: [{ value: '', disabled: true }]
)};
this.selectVehicleForm.get('Manufacturer').valueChanges.subscribe(value => {
if (value) {
this.selectVehicleForm.get('Model').enable();
} else {
this.selectVehicleForm.get('Model').reset('');
this.selectVehicleForm.get('Model').disable();
}
this.selectVehicleForm.updateValueAndValidity();
})
}
You can listen (change) on the FormControl Manufacturer and call enable()/disable() on the FormControl Model
See the Stackblitz
Relevant parts are :
HTML
<select formControlName="Manufacturer" (change)="onChangeManufacturer($event)">
<option *ngFor='let cars of cars$'>{{cars.Manufacturer}}</option>
</select>
Typescript
selectVehicleForm = new FormGroup({
Manufacturer: new FormControl(),
Model: new FormControl(),
});
ngOnInit() {
this.selectVehicleForm.controls['Model'].disable();
}
onChangeManufacturer(value) {
const formControlModel = this.selectVehicleForm.controls['Model'];
if(this.selectVehicleForm.controls['Manufacturer']) {
formControlModel.enable();
} else {
formControlModel.disable();
}
}

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

HTML Variables ignores double brackets

The actually problem was that my angular is not working at all
if you want to test this do this :
import { Component, OnInit} from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
console.log('test');
}
}
/////////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////////
I'm trying to create a dropdownlist with a name and value different from each other. In Visual studio 2015 the brackets at ">{{directionOption.name}}<" are shown grey as plain text
<select [(ngModel)]="direction">
<option *ngFor="#directionOption of directionOptions" [value]="directionOption.value">{{directionOption.name}}</option>
</select>
same result
<select [(ngModel)]="direction">
<option *ngFor="let directionOption of directionOptions" [value]="directionOption.value">{{directionOption.name}}</option>
</select>
export class AppComponent implements OnInit {
direction: any = { 'Left': 'L' };
directionOptions: any = [{ name: 'Left', value: 'L' }, { name: 'Right', value: 'R' }, { name: 'None', value: 'N' }];
}
The current result inside browser F12
<option *ngfor="#directionOption of directionOptions" [value]="directionOption.value">{{directionOption.name}}</option>
Use let keyword instead of #,
<option *ngfor="let directionOption of directionOptions" [value]="directionOption.value">{{directionOption.name}}</option>
update
Angular2 doesn't process bindings added dynamically to the DOM, only when they are added statically to a components template.
original
directionOptions should look like
directionOptions: any = [{ name: 'Left' , value: 'L' }, { name: 'Right' , value: 'R' }, { name: 'None' , value: 'N' }];