1

I have an Angular UI where clicking an edit button transforms the member name heading into a form where you can edit and update the name. I want the form to be pre-filled with the existing name.

However, the problem occurs with the value="{{member.name}}" line in the code snippet below. The form simply appears blank. Why?

Using placeholder="{{member.name}}"sets the value correctly, but placeholder isn't the behavior I want.

<h4 *ngIf="!editMode">{{member.name}}</h4>
<form *ngIf="editMode" #f="ngForm" (ngSubmit)="onEdit(f)">
    <input type="text" value="{{member.name}}" ngModel name="name">
    <button type="submit">Update</button>
</form>
yayvon
  • 35
  • 5

2 Answers2

1

To set the value of an input field use [ngModel] directive and put the variable as parameter. Usually one wants a "two way binding", that's why the [] and () are mixed.

<form *ngIf="editMode" #f="ngForm" (ngSubmit)="onEdit(f)">
    <input type="text" [(ngModel)]="member.name" name="name">
    <button type="submit">Update</button>
</form>

It's possible to only use [] to only "set" the value of the input. See the following SO-question for details: Difference between [(ngModel)] and [ngModel] for binding state to property?

Source: https://angular.io/api/forms/NgModel

Capricorn
  • 2,061
  • 5
  • 24
  • 31
0

I came up to this answer looking for set the placeholder with a variable but didn't work with the solution above.

I solved with property binding, using [placeholder]="myVar" with this helpfull link

<form *ngIf="editMode" #f="ngForm" (ngSubmit)="onEdit(f)">
  <input type="text" [(ngModel)]="member.name" name="name" [placeholder]="myVar">
  <button type="submit">Update</button>
</form>

And the Angular component to set placeholder text:

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

@Component({
  selector: 'app-input-placeholder',
  templateUrl: './input-placeholder.component.html',
  styleUrls: ['./input-placeholder.component.scss']
})

export class PlaceholderComponent {
  myVar = 'Please enter your name here';
}
Alex
  • 643
  • 7
  • 17