0

I have a dropdown and i have done validation using formcontrolname. I also wanted to display the selected dropdown. So i used ngModel for this to happen. But I received an error saying

It looks like you're using ngModel on the same form field as formControlName. Support for using the 
ngModel input property and ngModelChange event with reactive form directives has been deprecated in 
Angular v6 and will be removed in Angular v7. 

How can i achieve both validation and displaying selected dropdown using formControlName

My HTML code

 <nb-select selected="1" id="doctor" formControlName="titleName" required (change)="changeTitle($event)"
 [class.is-invalid]="form.get('titlename').invalid && form.get('titlename').touched" [(ngModel)]="selectedtitle">

   <nb-option *ngFor="let title of Title" [value]="title">{{title}}</nb-option>
 </nb-select>

<p>{{selectedtitle}}</p>

My .ts file

Title: any=['Mr.', 'Ms.', 'Mrs.'];
selectedtitle = this.Title[0];

changeTitle(e){
    console.log(e)
    this.titleName.setValue(e.target.value,{
      onlySelf: true
    })
  }

  get titleName() {
    return this.form.get('title');
  }
3
  • Don't use reactive form and template driven form together. You can set Default value using reactive form itself Commented Mar 24, 2020 at 13:13
  • I'm not asking about default value. I want to display the selected dropdown Commented Mar 24, 2020 at 13:35
  • Since you have created getter titleName. you can use that to acces selected value. Commented Mar 24, 2020 at 13:39

1 Answer 1

1

You dont need to use [(ngModel)] for this purpose

just use

<p>{{ form.value.title }}</p?

or

<p>{{ form.controls['title'].value }}</p>

Assuming you have formgroup as form

<form [formGroup]="form" (ngSubmit)="onSubmit()">

if you want to show errors validation

  <span class="error" *ngIf="form.controls['title'].errors.required">This field is required</span>
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, please help me out with this question. stackoverflow.com/questions/60839181/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.