angular - 有没有一种简单的方法来覆盖基本指令?
问题描述
我正在寻找一种简单的方法来覆盖开箱即用提供的指令的行为,例如ngIf
所以我可以制作一个子指令并扩展行为,然后声明为原生指令。
PS:我知道覆盖标准功能是非常糟糕的做法,但我这样做只是为了学习/研究目的。
解决方案
你可以考虑写你自己的 ngIf 像 myIf
import { Directive, Input, ElementRef, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[myIf]'
})
export class MyIfDirective {
constructor(
private element: ElementRef,
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {
}
@Input()
set myIf(val) {
if(val) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
然后
<div *myIf="isVisible">
Hi there!
</div>
或者这会有所帮助
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import {NgIf} from "@angular/common"
@Directive({
selector: '[ngIf][myNgIf]'
})
export class myNgIf extends NgIf {
@Input() myNgIf: boolean;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) {
super(viewContainer, templateRef);
}
@Input()
set ngIf(val) {
if (val) {
...
} else {
this.viewContainer.clear();
}
}
推荐阅读
- python - 如何检测python-requests中的断开连接保持连接?
- c# - 对大小为 n 的数组进行左旋转操作移位
- webpack - Sequelize 无法加载 mariadb
- keras - Keras:ImageDataGenerator 生成的图像中的奇怪伪影
- php - TCPDF - 在多页上拆分表格并按页面显示总计
- java - 成员变量的局部变量的目的是什么?
- enums - 使 cython 枚举可见
- java - 用于同步切换类型的 IotCentral 设备属性的报告属性的数据类型
- visual-studio-code - VS Code:如何在选择时禁用复制
- ajax - WordPress REST API 身份验证