我正在尝试构建一个Angular Directive,我希望根据一些配置输入值实现以下内容
disabled
等属性属性
醇>
根据我对Angular的一点知识和理解,我们可以使用Structural Directive获得第一个要求。第二和第二的地方我们需要创建Attribute Directive的第三个要求。这是我对两个指令的实现
import { SomeService } from './some.service';
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({ selector: '[structuralBehaviour]' })
export class StructuralBehaviourDirective {
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef, private someService: SomeService) { }
@Input() set structuralBehaviour(config: any) {
// 1st Condition
// Conditional Stamentents using config and somService
// For the purpose to decide whether to add template in
// DOM or not
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
这是属性指令
import { SomeService } from './some.service';
import { Directive, ElementRef, Input, Renderer } from '@angular/core';
@Directive({ selector: '[attributeBehaviour]' })
export class AttributeBehaviourDirective {
constructor(private _renderer: Renderer, private _el: ElementRef,
private someService: SomeService) { }
@Input() set attributeBehaviour(config: any) {
// 2nd Condition
// Conditional Stamentents using config and someService
// For the purpose to set style visibility property to hidden
this._el.nativeElement.style.visibility = 'hidden';
// 3rd Condition
// Conditional Stamentents using config and someService
// For the purpose to add disabled attribute
this._renderer.setElementProperty(this._el.nativeElement, 'disabled, true);
}
}
目前,我正在使用以下指令,这对我来说很好用
<button *structuralBehaviour="config" [attributeBehaviour]="config"
class="btn btn-primary">Add</button>
我在这里看到的是回答问题,是否可以将上述两个指令合并在一起并构建单个指令,以便我可以使用它们这样的
<button *singleBehaviour="config" class="btn btn-primary">Add</button>
答案 0 :(得分:2)
this.viewContainer.createEmbeddedView
返回包含EmbeddedViewRef
的{{1}}。您可以使用它来实现您的行为
rootNodes
<强> Plunker Example 强>
答案 1 :(得分:0)