【问题标题】:Angular: How to assigne value to variable in specific component from input of different templateAngular:如何从不同模板的输入中为特定组件中的变量赋值
【发布时间】:2019-01-06 18:10:32
【问题描述】:

我正在将 daterangepicker 作为 Angular 组件,它是 JS 库 (https://bootstrap-datepicker.readthedocs.io/en/latest/) 的包装器。我的问题是我不知道如何将 datepicker 输入中的值传递给其他组件中的变量(我想在其中使用我的 daterangepicker)。这就是我制作 daterangepicker 组件的方式:

import {AfterViewInit, Component, Input, OnInit} from '@angular/core';
import 'bootstrap-datepicker';
declare var $;


@Component({
    selector: 'cb-daterangepicker',
    templateUrl: './daterangepicker.component.html',
    styleUrls: ['./daterangepicker.component.scss']
})
export class DaterangepickerComponent implements OnInit, AfterViewInit {

    @Input()
    datepickerOptions: DatepickerOptions;

    constructor() { }

    ngOnInit() { }

    ngAfterViewInit(): void {

        $('.input-daterange').datepicker(this.datepickerOptions).on('changeDate', function() {
            var startDate =$('#start').datepicker('getDate');
            var endDate= $('#end').datepicker('getDate');
            console.log(startDate + " to " + endDate);
        });
    }
}

模板看起来像这样:

<div class="input-daterange input-group" id="datepicker">
    <input type="text" class="input-sm form-control" id="start" />
    <span class="input-group-addon">to</span>
    <input type="text" class="input-sm form-control" id="end" />
</div>

也许我做错了什么,但 console.log 返回了正确的值,所以我认为这两件事都很好。

我想要达到的目标: 在其他组件中-让我将其命名为“exampleComponent”,我有两个变量:startDate 和 endDate,每次更改值时,我都需要将在 daterangepicker 中选择的值传递给该变量。我想做什么?

【问题讨论】:

  • 我认为消费组件应该使用 Angular 形式的日期选择器。您可能需要让日期选择器实现 ControlValueAccessor:angular.io/api/forms/ControlValueAccessor
  • 好的,我实现了这个,但接下来呢?我在其他组件 html 和 daterangepickerOptions 中使用指令将它们传递到指令中。但是 exampleComponent 中的 startDate 和 endDate 这两个字段呢?

标签: javascript html css angular datepicker


【解决方案1】:

你必须使用@Output 装饰器,

首先在类 DaterangepickerComponent 中创建新属性,将其标记为@Output 并将 EventEmitter Instance 分配给它(您需要导入它)

@Output dateOutput = new EventEmitter<Object>();

当你有时在你的回调中下一步

console.log(startDate + " to " + endDate);

你需要使用:

this.dateOutput.emit({startDate, endDate});

当你使用你的组件时,你需要将回调属性传递给它

<cb-daterangepicker dateOutput="callback($event)"> 

之后,当您在 datepicker 中选择日期时,将调用回调方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多