如何正确使用addEventListener和removeEventListener函数?

时间:2017-11-09 23:00:56

标签: angular typescript

我花了很多时间来解决这个问题。我需要添加按钮onclick事件,它应该动态更改。

我的子组件是carts.component.ts

import { Component, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { CartService } from '../Service/cart.service';
import { FormBuilder, FormGroup, FormArray, Validators, ReactiveFormsModule } from '@angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { ICart } from '../Models/cart';
import { DbOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';

@Component({
    templateUrl: 'app/Components/carts.component.html'
})
export class CartsComponent implements OnInit, AfterViewChecked {

    @ViewChild('modal') modal: ModalComponent;
    carts: ICart[];
    cart: ICart;
    msg: string;
    indLoading: boolean = false;
    cartFrm: FormGroup;
    dbOps: DbOperation;
    modalTitle: string;
    modalBtnTitle: string;

    getCartProducts: EventListener;
    hideCartProducts: EventListener;   
    test: boolean = false; 

    ngOnInit(): void {        
        Global.titleService.setTitle("Корзины");  

        this.cartFrm = this.fb.group({
            Id: [''],
            Name: ['', Validators.required],
            Description: ['']
        });

        this.LoadCarts();

        this.getCartProducts = function (event: Event) {                     
            //for (let product of this.cart.Products) {                
                //event.srcElement.parentElement.parentElement.insertAdjacentHTML("afterend", "<tr><td>" + product.Name + "</td><td>" + product.Price + "</td></tr>");
            //}
            event.srcElement.textContent = "Скрыть продукты";
            event.srcElement.attributes.getNamedItem("title").value = "Скрыть продукты";

            /* This show me "show BUTTON", it is right */ event.srcElement.parentElement.parentElement.insertAdjacentHTML("afterend", "<div>show " + event.srcElement.tagName + "</div>");

            /* This doesn't work, HELP ME, I DON'T UNDERSTAND WHY */ event.srcElement.removeEventListener("click", this.getCartProducts, false);
            /* This also doesn't work, HELP ME, I DON'T UNDERSTAND WHY */ event.srcElement.addEventListener("click", this.hideCartProducts(event), false);
        };

        this.hideCartProducts = function (event: Event) {
            event.srcElement.textContent = "Показать продукты";
            event.srcElement.attributes.getNamedItem("title").value = "Показать продукты";

            event.srcElement.parentElement.parentElement.insertAdjacentHTML("afterend", "<div>hide</div>");

            event.srcElement.removeEventListener("click", this.hideCartProducts, false);
            event.srcElement.addEventListener("click", this.getCartProducts, false);
        }        
    }

    ngAfterViewChecked() {
        if (!this.test) {
            let btnsShow = document.getElementsByClassName("btn-show");

            if (btnsShow.length != 0)
                this.test = true;

            var x = document.createElement("div");  // Creates a new <div> node
            x.textContent = "Hello, world " + btnsShow.length;         // Sets the text content
            document.body.appendChild(x);

            for (let i = 0; i < btnsShow.length; i++) {
                /* THIS BIND ONCLICK TO BUTTONS */ btnsShow[i].addEventListener("click", this.getCartProducts, false);
            }
        }
    }

    LoadCarts(): void {
        this.indLoading = true;
        this._cartService.get(Global.CARTS_USER_ENDPOINT)
            .subscribe(carts => { this.carts = carts; this.indLoading = false; },
            error => this.msg = <any>error);
    }

    SetControlsState(isEnable: boolean) {
        isEnable ? this.cartFrm.enable() : this.cartFrm.disable();
    }

    addCart() {
        this.dbOps = DbOperation.create;
        this.SetControlsState(true);
        this.modalTitle = "Добавить корзину";
        this.modalBtnTitle = "Добавить";
        this.cartFrm.reset();
        this.modal.open();
    }

    editCart(id: number) {
        this.dbOps = DbOperation.update;
        this.SetControlsState(true);
        this.modalTitle = "Изменить корзину";
        this.modalBtnTitle = "Изменить";
        this.cart = this.carts.filter(x => x.Id == id)[0];             
        this.cartFrm.setValue({
            Id: this.cart.Id,
            Name: this.cart.Name,
            Description: this.cart.Description
        });
        this.modal.open();
    }

    deleteCart(id: number) {
        this.dbOps = DbOperation.delete;
        this.SetControlsState(false);
        this.modalTitle = "Вы действительно хотите удалить эту корзину?";
        this.modalBtnTitle = "Удалить";
        this.cart = this.carts.filter(x => x.Id == id)[0];
        this.cartFrm.setValue({
            Id: this.cart.Id,
            Name: this.cart.Name,
            Description: this.cart.Description
        });
        this.modal.open();
    }

    onSubmit(formData: any) {
        this.msg = "";

        switch (this.dbOps) {
            case DbOperation.create:
                this._cartService.post(Global.CARTS_USER_ENDPOINT, formData._value).subscribe(
                    data => {
                        if (data == 1) //Успешно
                        {
                            this.msg = "Корзина успешно добавлена.";
                            this.LoadCarts();
                        }
                        else {
                            this.msg = "При добавлении корзины возникли некоторые проблемы!"
                        }

                        this.modal.dismiss();
                    },
                    error => {
                        this.msg = error;
                    }
                );
                break;
            case DbOperation.update:
                this._cartService.put(Global.CARTS_USER_ENDPOINT, formData._value.Id, formData._value).subscribe(
                    data => {
                        if (data == 1) //Успешно
                        {
                            this.msg = "Корзина успешно изменена.";
                            this.LoadCarts();
                        }
                        else {
                            this.msg = "При изменении корзины возникли некоторые проблемы!"
                        }

                        this.modal.dismiss();
                    },
                    error => {
                        this.msg = error;
                    }
                );
                break;
            case DbOperation.delete:
                this._cartService.delete(Global.CARTS_USER_ENDPOINT, formData._value.Id).subscribe(
                    data => {
                        if (data == 1) //Успешно
                        {
                            this.msg = "Корзина успешно удалена.";
                            this.LoadCarts();
                        }
                        else {
                            this.msg = "При удалении корзины возникли некоторые проблемы!"
                        }

                        this.modal.dismiss();
                    },
                    error => {
                        this.msg = error;
                    }
                );
                break;
        }
    }
    constructor(private fb: FormBuilder, private _cartService: CartService) { }    
}

代码将函数getCartProducts绑定到事件“onclick”,但函数中的某些行(我用注释标记它们)不起作用。

carts.component.html

<div class="col-md-12" id="time">
    <div class="panel panel-primary">
        <div class='panel-body'>
            <div class='table-responsive'>
                <div style="padding-bottom: 10px">
                    <button class="btn btn-primary" (click)="addCart()">Добавить</button>
                </div>
                <div class="alert alert-info" role="alert" *ngIf="indLoading">
                    <img src="../../generalLoad.gif" class="generalLoad" />
                </div>
                <div *ngIf='carts && carts.length==0' class="alert alert-info" role="alert">Корзин не найдено!</div>
                <table class='table table-striped' *ngIf='carts && carts.length'>
                    <thead>
                        <tr>
                            <th>Название</th>
                            <th>Описание</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let cart of carts">
                            <td>{{cart.Name}}</td>
                            <td>{{cart.Description}}</td>
                            <td>
                                <!-- BUTTON WHICH I NEED TO BIND ONCLICK EVENT -->
                                <button title="Показать продукты" class="btn btn-show">Показать продукты</button>
                                <button title="Изменить" class="btn btn-primary" (click)="editCart(cart.Id)">Изменить</button>
                                <button title="Удалить" class="btn btn-danger" (click)="deleteCart(cart.Id)">Удалить</button>
                            </td>                          
                        </tr>
                    </tbody>
                </table>
                <div>
                </div>
            </div>
            <div *ngIf="msg" role="alert" class="alert alert-info alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-label="Закрыть"><span aria-hidden="true">&times;</span></button>
                <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                <span class="sr-only">Ошибка:</span>
                {{msg}}
            </div>
        </div>
    </div>
</div>

<modal #modal>
    <form novalidate (ngSubmit)="onSubmit(cartFrm)" [formGroup]="cartFrm">
        <modal-header [show-close]="true">
            <h4 class="modal-title">{{modalTitle}}</h4>
        </modal-header>
        <modal-body>
            <div class="form-group">
                <div>
                    <span>Название</span>
                    <input type="text" class="form-control" placeholder="Название" formControlName="Name">
                </div>
                <div>
                    <span>Описание</span>
                    <textarea class="form-control" placeholder="Описание" formControlName="Description"></textarea>                   
                </div>
            </div>
        </modal-body>
        <modal-footer>
            <div>
                <a class="btn btn-default" (click)="modal.dismiss()">Назад</a>
                <button type="submit" [disabled]="cartFrm.invalid" class="btn btn-primary">{{modalBtnTitle}}</button>
            </div>
        </modal-footer>
    </form>
</modal>

我希望有人能够帮助我并解释为什么addEventListener和removeEventListener不起作用。谢谢大家!

0 个答案:

没有答案