您好,登錄后才能下訂單哦!
要在Angular中實現(xiàn)自定義結(jié)構(gòu)性指令,可以按照以下步驟進(jìn)行:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appCustomDirective]'
})
export class CustomDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { }
@Input() set appCustomDirective(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomDirective } from './custom.directive';
@NgModule({
declarations: [
CustomDirective
],
imports: [
CommonModule
],
exports: [
CustomDirective
]
})
export class SharedModule { }
<div *appCustomDirective="condition">
<!-- Your content here -->
</div>
在上面的代碼中,當(dāng)condition
為true時,<div>
元素會被動態(tài)創(chuàng)建并顯示在模板中,否則會被清除。這樣就可以實現(xiàn)自定義結(jié)構(gòu)性指令在Angular中的使用。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。