【问题标题】:Materializecss Datepicker isn't returning value to Angular 8 reactive formMaterializecss Datepicker 没有将值返回到 Angular 8 反应形式
【发布时间】:2020-01-07 18:06:47
【问题描述】:

我在 Angular 8 项目中使用 materializecss 1.0.0,但遇到了问题。

我制作了一个带有 datepickerformselect 的角度响应式表单,但是 formGroup 中的“valueChanges”变量仅在 formselect 时触发> 更新其值,但 datepicker 值仍然相同。

重要 1:我知道有一个名为 angular2-materialize 的包,但它只适用于 0.100 版

重要 2:我正在尝试使用没有 JQuery 的 materialize-css,因为它现在是一个可选包。

form-request-card.component.html(部分)

[...]
<form [formGroup]="formDOM">          
            <div class="row">
                <!-- Datepicker para data inicial (start) -->
                <div class="form-group col s12">
                    <label>Data inicial</label>
                    <input #startinput class="form-control datepicker" formControlName="start" type="date">
                </div>
    
                <!-- Selector referente a metrica utilizada na analise dos dados (metric) -->
                <div class="form-group input-field col s12">
                    <select #metricinput class="form-control" formControlName="metric">
                        <option value="" disabled selected>Selecione o valor</option>
                        <option *ngFor="let metric of metricArray" [value]=metric>
                            {{metric}}
                        </option>
                    </select>
                    <label>Métrica</label>
                </div>
           </div>
</form>
[...]

form-request-card.component.ts

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

declare const M: any;

@Component({
  selector: 'app-form-request-card',
  templateUrl: './form-request-card.component.html',
  styleUrls: ['./form-request-card.component.css']
})

export class FormRequestCardComponent implements OnInit, AfterViewInit {

  @ViewChild('startinput', {static: true}) startInput: ElementRef;
  @ViewChild('metricinput', {static: true}) metricInput: ElementRef;

  readonly title = "test";

  metricArray: string[];
  formDOM: FormGroup;

  constructor(private _formBuilder: FormBuilder) { 
    this.metricArray = ["op1", "op2", "op3"];
  }

  ngOnInit() {
    this.formDOM = this._formBuilder.group({ start: [null], metric: [null] });
    this.formDOM.valueChanges.forEach( (value) => console.log(JSON.stringify(value)) );
  }

  ngAfterViewInit() {
    let pickerProperty = {
      autoClose: true, format: "yyyy-mm-dd", container: "body"
    };

    M.Datepicker.init(this.startInput.nativeElement, pickerProperty);
    M.FormSelect.init(this.metricInput.nativeElement, {});
  }
}

当 valueChanges 被触发时,console.log 结果是:

    {"start":null,"metric":"op1"}

有没有“角度方式”来解决这个问题?

现在谢谢。

【问题讨论】:

    标签: angular materialize


    【解决方案1】:

    我建议在FormGroup 中使用FormControls,并完全跳过ViewChild 解决方案。 您可以像这样创建formDOM

    this.formDOM = this._formBuild.group({
       start: new FormControl(null),
       metric: new FormControl(null),
    })
    

    然后获取它们的值onChange 或类似这样的一些用户操作:

    console.log(this.formDOM.controls['start'].value);
    console.log(this.formDOM.controls['metric'].value);
    

    FormControls 也有自己的 onChange 事件,因此您可以使用 this.formDOM.controls['start'].valueChangesthis.formDOM.controls['metric'].valueChanges 独立订阅它们。

    使用此解决方案,您可以从 .ts 文件中删除 @ViewChild 行,并从 HTML 中删除 #startinput#metricinput 参数

    注意:FormControls 的另一个有用之处是您可以使用所谓的 validators 来强制输入或限制可能的值。 FormControl 在创建时接受一组验证器(和其他选项)作为第二个参数,类似于:start: new FormControl(null, [Validators.required])Validators 可以从 @angular/forms 导入,它包含一些基本的验证方法,但你也可以编写您自己的验证器并在您的组件中使用它)。在文档中了解更多信息:FormControlValidators

    【讨论】:

    • 澄清一下:您还必须从 @angular/forms 导入 FormControl
    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2020-11-23
    • 2018-11-30
    • 2020-11-07
    相关资源
    最近更新 更多