简体   繁体   中英

Setting a default placeholder date using Angular and ng-bootstrap

I am trying to set a placeholder date (now) for a datepicker, however can't work out how to do it.

Please help.

import {Component} from '@angular/core';
import { NgbDateCustomParserFormatter} from 'dateformat';

@Component({
  selector: 'ngbd-datepicker-popup',
  templateUrl: './datepicker-popup.html',

   valuedate = new Date();

})


export class NgbdDatepickerPopup {
  model = {year: 2017, month: 8, day: 8};
}
<div class="input-group">
  <input type="text" ngbDatepicker placeholder="{{model}}" class="form-control" #d="ngbDatepicker" [(ngModel)]="model" />
  <button (click)="d.toggle()">Toggle</button>

</div>

So a couple of things here:

A) "AngularJS" generally refers to Angular 1.x, and this is clearly Angular 2+ you're working with here

B) Judging by the fact that you are trying to place valuedate inside of your Component decorator instead of as a property inside your class definition, I'd say you need to learn a lot about Angular before wanting to tackle building your own component to do this. There are several component libraries that will give you a datepicker including Angular Material and Kendo .

C) The double curly brace syntax is for interpolation, which essentially inserts text. If you really are needing to roll your own component here, something like this might work (note: uses the momentjs library):

 <input type="text" ngbDatepicker placeholder="placeholder" class="form-control" [(ngModel)]="valuedate" /> 

 import {Component} from '@angular/core'; import { NgbDateCustomParserFormatter} from 'dateformat'; import * as moment from 'moment-mini'; @Component({ selector: 'ngbd-datepicker-popup', templateUrl: './datepicker-popup.html', }) export class NgbdDatepickerPopup { valuedate = new Date(); placeholder: string = moment().format('MM/DD/YYYY'); } 

D) There are some other issues with your code. You need to implement the ControlValueAccessor interface for ngModel to work in a custom component like that.

Create a format for your placeholder:

present : Date  = new Date();
model           = 
{
    year : this.present.getFullYear(), 
    month: this.present.getMonth()+1, 
    day  : this.present.getDate()
};

placeHolderText = this.model.year + '-' + this.model.month + '-' + this.model.day;

Then

<input type="text" ngbDatepicker placeholder="placeHolderText" ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM