Home > Blockchain >  NgMode Value Overrides placeholder on text input
NgMode Value Overrides placeholder on text input

Time:06-21

I have an Angular Form as seen below,

<div >
    <form #noteForm="ngForm" (ngSubmit)="onSubmit(noteForm)">
        <div >
            <label >Title</label>
            <div >
                <input type="text" name="title" required  ngModel="note.title" placeholder="Input Title">
            </div>
        </div>
        <br>
        <div >
            <label >Body</label>
            <div ><textarea  required name="body" ngModel="note.body"></textarea></div>
        </div>

        <div >
            <div >
                <button  type="button">Cancel</button>
            </div>
            <div >
                <button  type="submit">Save</button>
            </div>
        </div>

    </form>

</div>

and typescript equivalent,

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Note } from 'src/app/shared/note.model';

@Component({
  selector: 'app-note-details',
  templateUrl: './note-details.component.html',
  styleUrls: ['./note-details.component.scss']
})
export class NoteDetailsComponent implements OnInit {
  note: Note = {
    title: '',
    body: ''
  };
  constructor() { }

  ngOnInit(): void {
    this.note = new Note();
  }

  onSubmit(form: NgForm){
    console.log(form);
  }

}

The issue i am having now is that on the form interface, the placeholder by default is the value of the property ngModel which is note.title for input title and note.body for input body.

I have tried to add placeholder="my placeholder" on the input tag but still it overrides it.

CodePudding user response:

you forgot to add the binding tag [()] on your ngModel in your HTML.

Instead of this :

<input type="text" name="title" required  ngModel="note.title" placeholder="Input Title">

Try this :

<input type="text" name="title" required  [(ngModel)]="note.title" placeholder="Input Title">

I created a stackblitz https://stackblitz.com/edit/angular-ivy-ivz1ei?file=src/app/app.component.html to show you the result

  • Related