【发布时间】:2017-10-11 20:31:04
【问题描述】:
我正在尝试构建一个 Angular 指令,我想根据一些配置输入值实现以下目标
- 根据输入值在 DOM 中添加元素。 (就像 ngIf)
- 如果元素呈现,则为其添加一些样式
- 向元素添加一些属性属性,例如
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>
【问题讨论】:
-
Ajax,您使用的是 jQuery,还是可以将它包含在您的项目中? jQuery 可以快速解决您的问题。
-
不,我没有使用 JQuery,尝试仅使用 Angular Typescript 代码来实现它。
标签: angular typescript angular-directive