Nap*_*pas 7 angular-directive angular2-directives angular
我有一个自定义指令,应该能够根据其他条件添加/删除类.
即
@Directive({
selector: '[customDirective]'
})
export class CustomDirective {
constructor(service: SomService) {
// code to add class
if (service.someCondition()) {
// code to remove class
}
}
}
Run Code Online (Sandbox Code Playgroud)
lex*_*ith 23
如果您不想使用该ngClass指令(提示:您可以将函数传递给[ngClass]="myClasses()"模板中的内联乱码),您可以使用Renderer2它来添加一个或多个类:
export class CustomDirective {
constructor(private renderer: Renderer2,
private elementRef: ElementRef,
service: SomService) {
}
addClass(className: string, element: any) {
this.renderer.addClass(element, className);
// or use the host element directly
// this.renderer.addClass(this.elementRef.nativeElement, className);
}
removeClass(className: string, element: any) {
this.renderer.removeClass(element, className);
}
}
Run Code Online (Sandbox Code Playgroud)
mtp*_*ltz 12
当您在 Angular 中使用指令时,您可能希望使用@HostBinding, 并绑定到class.your-class以便能够根据谓词添加/删除您的类。您不需要在 DI 中Renderer2有效地添加/删除类。
例如,当使用 Bootstrap 和 Reactive Forms 并且您想指示有效或无效的表单字段时,您可以执行以下操作:
import { Directive, Self, HostBinding, Input } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appCheckFormFieldValidity]'
})
export class CheckFormFieldValidity{
@Input() public class: string;
constructor(
@Self() private ngControl: NgControl
) { }
@HostBinding('class.is-valid')
public get isValid(): boolean {
return this.valid;
}
@HostBinding('class.is-invalid')
public get isInvalid(): boolean {
return this.invalid;
}
public get valid(): boolean {
return this.ngControl.valid &&
(this.ngControl.dirty || this.ngControl.touched);
}
public get invalid(): boolean {
return !this.ngControl.pending &&
!this.ngControl.valid &&
(this.ngControl.touched || this.ngControl.dirty);
}
}
Run Code Online (Sandbox Code Playgroud)
这不是一个严格的例子,但它说明了 的使用@HostBinding,我在一个StackBlitz 中创建了这个例子
| 归档时间: |
|
| 查看次数: |
14457 次 |
| 最近记录: |