父组件和指令之间的Angular2双向数据绑定

时间:2016-01-13 08:12:14

标签: typescript angular angular2-directives

请参阅下面的更新

仍在使用Angular2 Beta,我试图实现一个"编辑器"组件模板包含一个包装Ace编辑器的指令。因此,"编辑" component是Ace包装器指令的父级,我想从指令中获取代码或将代码设置到其中。

虽然指令单独工作正常,但当我将其包含在此组件中时,我什么也没有显示;但浏览器的控制台中没有显示任何错误。您可以在此Plunker中找到 repro http://plnkr.co/edit/kzclJLIX6hRMWa14A0Pb

在我的实现中,包含Ace编辑器的ace.directive指令包含text属性和textChanged事件。

import {Component,Directive,EventEmitter,ElementRef} from 'angular2/core';
declare var ace: any;

@Directive({
    selector: "ace-editor",
    inputs: [
        "text"
    ],
    outputs: [
        "textChanged"
    ]
})
export class AceDirective { 
    private editor : any;
    private settingText : boolean;
    public textChanged: EventEmitter<string>;

    set text(s: string) {
        let sOld = this.editor.getValue();
        if (sOld === s) return;

        this.settingText = true;
        this.editor.setValue(s);
        this.editor.clearSelection();
        this.editor.focus();
        this.settingText = false;
    }

    constructor(elementRef: ElementRef) {
        var dir = this;
        this.textChanged = new EventEmitter<string>();

        let el = elementRef.nativeElement;
        this.editor = ace.edit(el);

        this.editor.on("change", (e) => {
            if (dir.settingText) return;
            dir.textChanged.next(dir.editor.getValue());
        });
    }
}

editor.component组件使用该指令:它具有xml属性,表示正在编辑的XML代码。其模板包含如下指令:

<ace-editor id="editor" [text]="xml" (textChanged)="onXmlChanged()"></ace-editor>

即。指令的text属性绑定到父组件的xml 属性,指令的textChanged事件由父母处理 onXmlChanged功能。

这是一个双向数据绑定,AFAIK我也可以尝试:

<ace-editor id="editor" [(ngModel)]="xml"></ace-editor>

以下是编辑的代码:

import {Component,EventEmitter} from "angular2/core";
import {AceDirective} from "./ace.directive";

@Component({
    selector: "mit-editor",
    directives: [AceDirective],
    template: `<div>
      <ace-editor id="editor" [text]="xml" (textChanged)="onXmlChanged()"></ace-editor>
    </div>
    `,
    inputs: [
        "xml"
    ]
})
export class EditorComponent { 
    public xml: string;

    constructor() {
        this.xml = "";
    }

    public onXmlChanged(xml: string) {
        this.xml = xml;
    }
}

更新#1 出于某种原因,Plunker不会传输和加载我之前存在的.ts文件,因此我继续在本地进行故障排除。

关于这个问题,我发现我必须在模板中为调用添加$event参数(参见我的评论)。我的指示现在是:

import {Component,Directive,EventEmitter,ElementRef} from 'angular2/core';
declare var ace: any;

@Directive({
    selector: "ace-editor",
    inputs: [
        "text"
    ],
    outputs: [
        "textChanged"
    ]
})
export class AceDirective { 
    private editor : any;
    public textChanged: EventEmitter<string>;

    set text(s: string) {
        if (s === undefined) return;
        let sOld = this.editor.getValue();
        if (sOld === s) return;

        this.editor.setValue(s);
        this.editor.clearSelection();
        this.editor.focus();
    }

    get text() {
        return this.editor.getValue();
    }

    constructor(elementRef: ElementRef) {
        var dir = this;
        this.textChanged = new EventEmitter<string>();

        let el = elementRef.nativeElement;
        this.editor = ace.edit(el);
        let session = this.editor.getSession();
        session.setMode("ace/mode/xml");
        session.setUseWrapMode(true);

        this.editor.on("change", (e) => {
            let s = dir.editor.getValue();
            dir.textChanged.next(s);
        });
    }
}

编辑器组件模板包含如下指令:

<ace-editor id="editor" [text]="xml" (textChanged)="onXmlChanged($event)"></ace-editor>

无论如何,请注意,如果我现在尝试以编程方式设置编辑器的组件xml属性,则Angular启动并无限循环,因为更改会在ace编辑器上触发事件,该编辑器会发出设置xml财产再次出现,等等。可能只是我做错了什么,但目前我不得不在代码中使用这个黑客,当然我不喜欢它:):

// ...
export class EditorComponent { 
    private _xml: string;
    private _changeFrozenCount: number;

    public set xml(s: string) {
        this._xml = s; 
    }
    public get xml() : string {
        return this._xml;
    }

    constructor(private editorService: EditorService, private xmlService: XmlService) {
        this._xml = "";
    }

    public onXmlChanged(xml: string) {
        if (this._changeFrozenCount > 0) {
            this._changeFrozenCount--;
            return;
        }
        this._xml = xml;
    }

    public changeXml() {
        this._changeFrozenCount = 1;
        this._xml = "<sample>Hello</sample>"
    }
}

1 个答案:

答案 0 :(得分:3)

您忘了添加

directives: [EditorComponent]
在您的app.ts文件中

。目前,directives数组在您的plunker中为空([])。只需进行此更改就可以了,如果您设置onXmlChanged($event),当您在编辑器中输入时,它甚至会出错:)