首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >具有形式的反应性形式的NgbDatepicker :设置初始值

具有形式的反应性形式的NgbDatepicker :设置初始值
EN

Stack Overflow用户
提问于 2021-03-08 19:07:33
回答 2查看 1K关注 0票数 0

我试图以角度反应的形式使用ngbDatepicker,并希望能够显示初始值。

我的问题是非常类似于另一个和关键的区别,我也在使用正式,一个角包来自动生成表单。因为最初问题的答案是基于生成一个新的formControl并将它添加到表单中,在我的例子中,这是通过形式完成的,这就是为什么我在挣扎。

当您想要输入一个新值时,"component“通常起作用(因为这会触发我用来更改模型值的事件),但是初始值没有正确显示。虽然模型的值通常为"2020-07-05“,但如果用预兆进行检查,则从不会在输入字段中显示。如果我在NgbDate ()中将模型中的日期转换为ngOnInit({年份、月、日}),则此值将保持不变。

自动调用我的自定义组件(定义如下),该组件只包含字段,并将预先存在的窗体控件(包括模型)和字段配置绑定到输入字段。组件本身并没有什么作用,它包含了ngbDatepicker所必需的HTML和一个函数,在选择日期时,该函数将其从一个NgbDate ({年份、月、日})转换为字符串(“yyyy”),并确保它存储在模型中而不是NgbDate中。当您单击fa-日历图标时,它还会打开数据报警器:

代码语言:javascript
运行
复制
//formly-datepicker.component.html

<div class="form-group" [ngClass]="{'d-none': to.hidden}">
    <!-- Heading --> 
    <!-- to = TemplateOptions -->
    <label for="datepicker">
        <strong>
            {{to.label}}
            <span *ngIf="to.required">*</span>
        </strong>
    </label>

    <!-- Input -->
    <div class="input-group">
        <input
        class="form-control" 
        placeholder="yyyy-mm-dd" 
        name="datepicker" 
        [formControl]="formControl" 
        [formlyAttributes]="field" 
        ngbDatepicker 
        #datepickerInput="ngbDatepicker"
        (dateSelect)="inputDateToField($event)"
        >
        <div class="input-group-append">
            <div class="btn btn-outline-light fa fa-calendar" (click)="datepickerInput.toggle()"></div>
        </div>
    </div>
</div>


<ng-template #customDay let-date>
    <div class="datepicker-day btn-light">
        {{ date.day }}
    </div>
</ng-template>



//formly-datepicker.component.ts
import { Component, } from '@angular/core';
import { NgbDate } from '@ng-bootstrap/ng-bootstrap';
import { FieldType } from '@ngx-formly/core';

@Component({
  selector: 'app-formly-datepicker',
  templateUrl: './formly-datepicker.component.html',
  styleUrls: ['./formly-datepicker.component.scss']
})
export class FormlyDatepickerComponent extends FieldType{
  inputDateToField(event: NgbDate){
    this.model.session_date = `${event.year}-${event.month}-${event.day}`;
  }
}

我尝试过在ngOnInit()和ngAfterViewInit()中操作模型,我尝试过设置startDate,但在这种情况下似乎没有任何帮助。我在这里该怎么办?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-06-27 11:38:32

我敦促您更新NgBootstrap和For分子的信任(如果您还没有):

  1. 不要在组件中使用inputDateToField方法,而是为NgbDatePicker创建NgBootstrap推荐的这些NgbDatePicker。解析器将维护您在model中指定的格式,适配器将在UI中显示日期,同样是按照您的自定义。例如,我使用解析器转换后端提供的ISO字符串,以便在我的model中将其保存为‘YYYY’,并使用适配器将其显示为‘display’。
  2. 无论您在何处导入FormlyModule,都可以像这样更新配置(如果它不在AppModule中,则可能必须使用forChild):
代码语言:javascript
运行
复制
FormlyModule.forRoot({types: [{ name: 'date', component: FormlyDatepickerComponent, extends: 'input'}]})
  1. FormlyDatepickerComponent的模板中添加type="text" (可选)。
票数 1
EN

Stack Overflow用户

发布于 2021-06-27 12:39:43

你可以吃两杯:

1.-在创建表单时使用defaultValue a NgbDateStruct

代码语言:javascript
运行
复制
//I imagine you has an object "data" with a property "date" 
//in the way yyyy-mm-dd and create the field as
{
      key: 'date',
      type: 'input',
      defaultValue: {
           year:+data.date.substr(0,4),
           month:+data.date.substr(5,2),
           day:+data.date.substr(8,2)
      },
      templateOptions: {
        label: 'First Name (initialized via default value)',
      },
    },

在这种情况下,您总是使用“日期”-一个具有属性的对象-年、月、日,是的,FormControl可以存储一个对象,而不是"extrange“

2.-使用自定义适配器,该适配器使用的是字符串。有点复杂。您需要创建两个类:

CustomAdepter

代码语言:javascript
运行
复制
@Injectable()
export class CustomAdapter extends NgbDateAdapter<string> {

  readonly DELIMITER = '-';

  fromModel(value: string | null): NgbDateStruct | null {
    if (value) {
      let date = value.split(this.DELIMITER);
      return {
        day : parseInt(date[2], 10),
        month : parseInt(date[1], 10),
        year : parseInt(date[0], 10)
      };
    }
    return null;
  }

  toModel(date: NgbDateStruct | null): string | null {
    return date ? date.year+ this.DELIMITER+('00'+date.month).slice(-2) + this.DELIMITER + ('00'+date.day).slice(-2)   : null;
  }
}

和CustomDateParserFormatter (在输入输入时创建ngbDateStructurt)

代码语言:javascript
运行
复制
@Injectable()
export class CustomDateParserFormatter extends NgbDateParserFormatter {

  readonly DELIMITER = '-';

  parse(value: string): NgbDateStruct | null {
    if (value) {
      const separator=value.indexOf(".")>=0?".":value.indexOf("-")>=0?"-":value.indexOf("/")>=0?"/":null
      if (separator)
      {
      let date = value.split(separator);
      return {
        day : parseInt(date[2], 10),
        month : parseInt(date[1], 10),
        year : parseInt(date[0], 10)
      };
    }
    }
    return null;
  }

  format(date: NgbDateStruct | null): string {
    return date ? date.year+ this.DELIMITER+('00'+date.month).slice(-2) + this.DELIMITER + ('00'+date.day).slice(-2)   : "";
  }
}

然后,在组件中,您需要在模块中添加作为提供者的提供程序(您也可以在组件中添加作为提供程序)

代码语言:javascript
运行
复制
  providers: [
    {provide: NgbDateAdapter, useClass: CustomAdapter},
    {provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter}
  ]

现在您可以使用和您的模型或formControl将是一个字符串

叉式堆栈闪电战 -- ng-自助中的示例

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66535710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档