Home > Back-end >  Is it possible to pass an expression to the value attribute of an input tag?
Is it possible to pass an expression to the value attribute of an input tag?

Time:05-16

I tried the following, but the input field is blank.

<div >
          <label>First name:</label>
          <input type="text"  placeholder="John" formControlName="firstname" value="{{this.session_user[0].firstName}}">
</div>

CodePudding user response:

as I understood you want to set a default value to a FormControl value, I suppose your code is like this

    constructor(private fb: FormBuilder) { }

    public form: FormGroup = this.fb.group({
      firstname: ['This is the default value', // Default value
        [
          Validators.required // Validators here if needed
        ]
      ]
    });

To set a default value using FormBuilder, you can do it like the example above, of course, it can be a variable.

If you don't have the value yet when defining the FormGroup you can set the value whenever you want like so

    this.form.setValue({ firstname: "New value" });

Please note that the code above won't work if your input element is not inside a form element like in the example below

<form  [formGroup]="form">
          <label>First name:</label>
          <input type="text"  placeholder="John" formControlName="firstname">
</form>

No need to set a value attribute to the input element.

If you do not want to use FormControl then you can use ngModel

<input type="text" placeholder="John" [(ngModel)]="session_user[0].firstName">
  • Related