简体   繁体   中英

Angular: How to assigne value to variable in specific component from input of different template

I'm making daterangepicker as Angular Component that is wrapper of JS library ( https://bootstrap-datepicker.readthedocs.io/en/latest/ ). My problem is that I don't know how to pass value that is in input of datepicker to variable that is in other component (that where I want to use my daterangepicker). This is how I made daterangepicker component:

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);
        });
    }
}

And the template looks like this:

<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>

Maybe I did something wrong but console.log returns me correct values so I think this two things are good.

What I want to achive: In other component - let me name it 'exampleComponent' I have two variables: startDate and endDate, I need to pass values that I chose in daterangepicker to this variables every time I change the value. What I suppose to do?

You have to use @Output decorator,

First create new property in class DaterangepickerComponent mark it as @Output and assign EventEmitter Instance to it (you need import it)

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

Next in your callback when you have

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

You need to use:

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

When you use your component you need to pass callback attribute to it

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

after that when you choose date in datepicker callback method will be called

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