【问题标题】:Angular2 - Using directive to execute function in component losing scopeAngular2 - 使用指令在组件丢失范围内执行功能
【发布时间】:2018-01-20 03:55:03
【问题描述】:

我正在使用指令来显示对话框并确认继续,但是当从指令返回时,我的父组件失去了它的原始范围。 console.log 将返回未定义。

Process:当点击提交按钮时,appConfirm(指令)将处理点击事件并显示一个对话框以继续(是/否)。如果选择是,它将返回到我的父组件并执行提交功能,但范围丢失。

任何建议都会有所帮助。谢谢! Plunker 中的一个例子:https://plnkr.co/edit/CoNqz7yv8yaGMMRRarmu

模板:

<button [disabled]="disableButton" [(appConfirm)]="submit" style="primary" class="button-input btn btn-primary center-block">Submit</button>

指令:

import {Directive, HostListener, Input} from '@angular/core';
import {SharedService} from '../../core/shared.service';
import {MdDialog} from "@angular/material";
import {Continue, Confirmation, ContinueConfirmation} from "../../dialog/dialog.component";
import {FormComponent} from '../../form/form.component'

@Directive({
  selector: '[appConfirm]',
})
export class ConfirmDirective {
    constructor(
        private sharedService: SharedService,
        private dialog: MdDialog
    ) {}

  @Input() appConfirm = () => {};
  @Input() confirmMessage = 'Are you sure you want to do this?';
  @HostListener('click', ['$event'])
  confirmFirst(event: Event) {
        let dialogRef = this.dialog.open(Confirmation,{disableClose:true});
        dialogRef.afterClosed().subscribe(result=>{
               if(result) {
                  this.appConfirm();
                }

        });
  }
}

组件:

    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.css']
    })
    export class FormComponent {
        myButton: string = 'test'


        submit(){
console.log(this.myButton);
            }
    }

【问题讨论】:

标签: angular components angular2-directives angular2-components


【解决方案1】:

更新了 Plunker 现在可以使用了 LINK

visitRangle = () => { // change is here the fat arrow function
    console.log("My button should displaY: " + this.myButton);
    console.log('Visiting rangle');
    location.href = 'https://rangle.io';
  }

this 以这种方式使用时会失去作用域,因此您可以使用粗箭头函数自动将其绑定到类实例:

【讨论】:

  • Rahul,效果很好。谢谢你。我只是在我当地的环境中完成了它并且工作得很好。你能解释一下那个语法是做什么的吗?
  • @Tony 使用普通函数时,当您从指令返回时,此范围丢失且不受约束,您必须在方法末尾添加 .bind(this) 语法,或者您需要利用保持 this 值的胖箭头函数。喜欢这个问题的另一种example
  • 感谢您今天的快速帮助。你为我节省了大量时间。我认真地花了太多时间寻找这个答案。所以...谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-09-30
  • 2016-09-13
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多