Dis*_*ive 7 typescript angular
我创建了一个非常简单的调试组件,看起来像这样。
调试.component.html
<ng-container *ngIf="debugging">
<ng-content></ng-content>
</ng-container>
export class DebugComponent implements OnInit {
constructor() { }
ngOnInit() {
this.debugging = environment.debugging;
}
debugging: boolean;
}
Run Code Online (Sandbox Code Playgroud)
我像这样使用它
<app-debug>{{data | json}}</app-debug>
Run Code Online (Sandbox Code Playgroud)
我有一个环境变量,如果我想查看调试数据,我可以打开和关闭它。
export const environment = {
...
debugging: false,
...
}
Run Code Online (Sandbox Code Playgroud)
但是,我注意到当我渲染我的页面时,即使我有调试 = false,在我渲染的 HTML 中,我仍然看到这样的行
<app-debug _ngcontent-ydq-c8="" _nghost-ydq-c16=""><!--bindings={
"ng-reflect-ng-if": "false"
}--></app-debug>
Run Code Online (Sandbox Code Playgroud)
它是不可见的,但如果可能的话,我真的不希望我的调试代码被部署到 prod。
是否可以创建在特定条件下不呈现的组件?
您可以使用标准 DOM 方法“手动”删除调试组件主机。这是使用ElementRef
and 的一种方法removeChild
:
@Component({
selector: "app-debug",
template: `<ng-content></ng-content>`
})
export class DebugComponent implements OnInit {
debugging: boolean;
constructor(private elementRef: ElementRef) { }
ngOnInit() {
this.debugging = environment.debugging;
if (!this.debugging) {
let element = this.elementRef.nativeElement as HTMLElement;
element.parentElement.removeChild(element);
}
}
}
Run Code Online (Sandbox Code Playgroud)
有关演示,请参阅此 stackblitz。
子组件未包含在条件中。要完全禁用组件的渲染,应将条件应用于其选择器。
<ng-container *ngIf="debugging">
<app-debug>{{data | json}}</app-debug>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
或者
<app-debug *ngIf="debugging">{{data | json}}</app-debug>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
226 次 |
最近记录: |