在Angular 2中寻求有关指令实施的建议

时间:2017-05-11 23:49:46

标签: angularjs angular2-directives

我正在设计一个文本编辑组件。我已经将基本文本编辑器开发为最低限度可行的状态。现在,我希望能够添加实现字段文本/模板的功能。

我想象标记看起来像这样:

//basic text editor
<text-editor></text-editor>

//text editor with templates
<text-editor *templateProvider='templateProviderIdentifier'></text-editor>

//templates used on some future item
<not-yet-defined *templateProvider='templateProviderIdentifier'></not-yet-defined>

Directives的Angular2文档表明,Directive Constructor可以注入ElementRef,它可以让属性指令访问DOM元素,但属性指令如何获得对Controller的访问权限?

我不想编辑文本编辑器,因为模板可能会在别处使用。理想情况下,当属性出现在元素上时,指令会抓取关联的控制器并对其进行测试以获得可用的接口。如果检测到,它会通过将自身设置为元素上的行为修饰符或作为子对象的装饰器来修改Component。

我正在寻找有关属性指令如何访问Controller对象的信息以及您在我计划的方法中看到的任何提示或技巧或陷阱。

为了快速参考我读过的手册页,我提供了以下链接:

1 个答案:

答案 0 :(得分:0)

你可以使用带有输入值的angular2组件 像这样:

import { Component, OnInit, AfterViewChecked, AfterViewInit, Input, Output, ElementRef, EventEmitter } from '@angular/core';

@Component({
    selector: 'text-editor',
    template: require('./text-editor.component.html'),
    styleUrls: ['css/text-editor.css']
})
export class TextEditorComponent implements OnInit, AfterViewInit {

    @Input() templateProvider: any;
    @Output() something_for_output = new EventEmitter<any>();

    private el:HTMLElement;

    constructor(elementRef:ElementRef) {
    }

    ngAfterViewInit()
    {
    }

    ngAfterViewChecked()
    {
    }

    ngOnInit()
    {
    }
}

然后你可以在html中使用它:

 <text-editor [templateProvider]='something'></text-editor>