Angular 4 - find selected value in dropdown

强颜欢笑 提交于 2019-12-01 11:12:52

Use [value] instead of [ngValue] if you have a string or number as option value and don't want to use [(ngModel)]="...".

For object values you always should use [ngValue] though.

Since you are using Angular 4 Reactive Forms, you can do as follows:

let say you have this declaration in your typescript file for your component:

export class myComponent{
    myForm: FormGroup;

    ngOnInit(){
        this.myForm = new FormGroup({
            city: new FormControl('', Validators.required)
        }
    }

    onCitySelect($event:any){
        console.log(this.myForm.controls["city"].value);
    }
}

So you can use: this.myForm.controls["city"].value to access the selected value for city.

You can subscribe to formControl to fire a function on change of value and hence eliminating this

(change)="onCitySelect($event)" 

You can do this

this.myForm.get('city').valueChanges.subscribe(value=>{
     console.log(value);
})

where 'myForm' is your formGroup which has formControl 'city' so whenever you select value console.log() will happen hence no need to add onChange event

also instead of [ngValue] you can directly give [value] and what ever value you define here will get logged on change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!