防止 ng 模板以嵌入方式呈现



当我们使用ng-template创建预定义的模板时,内容会在使用前呈现。

当我们有像自动完成这样的元素调用远程 API 来获取数据时,这是一个问题。

我想防止这种情况,并仅在需要时呈现模板内容。

上下文:我有一个带有高级过滤器的表组件,当用户单击高级过滤器按钮时会打开该过滤器。我不希望在用户希望它这样做之前呈现过滤器。

编辑:我的问题不是等待数据到达。我的问题是,在用户打开表高级过滤器之前,我不想呈现自动完成。我的表是一个组件,它使用嵌入来获取过滤器。因此,我不想在使用表的组件中使用 IF,而是在控制何时显示筛选器 shhould 的表本身中使用 IF。

编辑:这是我部分的误解。 实际上,内容不会在viewInit上呈现。渲染发生在以隐藏模式挂载的表高级过滤器中。在我的ngTemplateOutlet中放置一个 *ngIf 解决了这个问题。

list-advanced-filter.component.html

<ng-container *ngIf="opened"
[ngTemplateOutlet]="templateRef"
[ngTemplateOutletContext]="{form: form}"
></ng-container>

Parent component.ts

{
public showTemplate:boolean;
public setShowTemplate(event){
this.showTemplate = event;
}

父母.html

<some-component *ngIf="showTemplate" (childShowTemplate)="setShowTemplate($event)"></some-component>

some-component.ts{

@Output()
childShowTemplate = new EventEmitter();
ngOnInit(){ // or any method you want like ngOnChanges or whatever
if(someCondition){
this.childShowTemplate.emit(true);
}else{
this.childShowTemplate.emit(false);
}
}
}

通过这种方式,孩子可以决定是否要渲染。

或者,您可以创建一个服务方法来处理这种情况...

最新更新