How to bind default value of input field to variable?
Asked Answered
W

4

14

When clicking a certain button in the UI of my Angular App, a dialog opens where the user can update his/her personal information. For the sake of simplicity I restrict the code in the following to his/her username. That is, I assume the user can only change his/her username in the dialog.

The code opening the dialog is the following:

openDialog() {

    this.dialog.open(UpdatePersonalDataComponent , {data: {
      firstName: this.firstName,
      username: this.username 
      }
    });

 }

The file update-personal-data.component.ts looks as follows:

import { Component, OnInit, Inject } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material';


@Component({
  selector: 'app-consultants-update-dialog',
  templateUrl: './consultants-update-dialog.component.html',
  styleUrls: ['./consultants-update-dialog.component.css']
})
export class UpdatePersonalDataComponent implements OnInit {


  constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }

  ngOnInit() {

  }

}

The file update-personal-data.component.html looks as follows at the moment:

<form #f="ngForm" (ngSubmit)="onSubmit(f)" fxLayout="column" fxLayoutAlign="center center"> 
    <h1 mat-dialog-title>Hi, {{ data.firstName }}. Update your username below.</h1>
    <mat-dialog-content fxLayout="column" fxLayoutAlign="center">
        <mat-form-field>
          <input 
            matInput 
            ngModel 
            #userName="ngModel" 
            name="userName" 
            type="text" 
            value="{{data.username}}"
            required>
        </mat-form-field>
    <mat-dialog-content   
    <mat-dialog-actions>
        <button mat-raised-button color="primary" [mat-dialog-close]>Cancel</button>   
        <button type="submit" mat-raised-button color="primary" [mat-dialog-close] [disabled]="f.invalid">Submit</button>    
    </mat-dialog-actions>
 </form>

As you can see, I want to set the default value of the input field equal to the old username, using the following code:

value="{{data.username}}"

However, this doesn't work. The input field is empty. I tried several other methods as well (e.g. [value]="{{data.username}}") but nothing worked. Does anybody know how to set the default value of the input field equal to the value of the variable data.username (which was passed to the dialog)?

Writhe answered 15/6, 2018 at 0:52 Comment(0)
E
17

I think that the better approach to do this is use the FormGroup of ReactiveForms Module. Something like this.

In your component.

 public form: FormGroup = new FormGroup({
    userName: new FormControl(''),
  });

In you HTML

<form [formGroup]="form">

<mat-form-field class="full-width">
        <input autocomplete="off" required matInput
               formControlName="userName" placeholder="Username">
</mat-form-field>

</form>

Now, you have control of your FORM to do this.

this.form.setValue({
  userName: YOUR_VALUE,
});
Ethaethan answered 15/6, 2018 at 3:56 Comment(1)
I was trying to set a default value in a matInput textbox using this: tribeForm: FormGroup = new FormGroup({ tribeName: new FormControl('WOW default'), }); but it was not working. I will just use a matSelect. Thanks for this "this.form.setValue"Icken
B
9

This will work, use ngmodel

<input matInput
[(ngModel)]="data.username" 
#userName="ngModel" 
name="userName" 
type="text" 
required>
Beatabeaten answered 15/6, 2018 at 6:17 Comment(1)
Can't bind to 'ngModel' since it isn't a known property of 'input' - i got this error. thanksMaddox
P
7

If you don't want to use formGroup, simple use following in your HTML <input>

<mat-form-field>
   <input matInput [value]="username"
          type="text" required>
</mat-form-field>

And your component:

export class UpdatePersonalDataComponent implements OnInit {

  constructor(@Inject(MAT_DIALOG_DATA) public data: any) {

    this.username = data.username;

  }

  ngOnInit() {

  }
Piquet answered 24/1, 2020 at 12:11 Comment(0)
C
5

As per the answer given by @William Aguera, I am just editing last part of answer:

this.form.patchValue({
userName: YOUR_VALUE,
});

Here I have only replaced setValue with patchValue. I often used this in editing forms.

Chromatic answered 5/8, 2019 at 12:54 Comment(1)
setValue works if it is the only item in your form. patchValue is effective when you want to set only some of the form elements.Secondly

© 2022 - 2025 — McMap. All rights reserved.