我试图制作一个使用ngTemplateOutlet来挑选ng-template的组件,但是我就是不明白为什么*ngTemplateOutlet在这里不能工作(但是ngTemplateOutlet可以工作)。
以下是我的代码
demo-frame.component.html:
<div class="frame-wrapper">
<ng-container [ngTemplateOutlet]="(windowWidth < 480)? this.realView : this.shelledView">
<ng-template #realView>
realView work!!
</ng-template>
<ng-template #shelledView>
shelledView work!!
</ng-template>
</ng-container>
</div>demo-frame.component.ts:
import { Component, OnInit, ViewChild, TemplateRef, HostListener} from '@angular/core';
@Component({
selector: 'app-demo-frame',
templateUrl: './demo-frame.component.html',
styleUrls: ['./demo-frame.component.scss']
})
export class DemoFrameComponent implements OnInit {
public windowWidth : number;
@ViewChild('realView') realView : TemplateRef<any>;
@ViewChild('shelledView') shelledView : TemplateRef<any>;
constructor() { }
getWindowWidth(){
this.windowWidth = window.innerWidth;
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.getWindowWidth();
}
ngOnInit() {
this.getWindowWidth();
}
}实际上我刚接触Angular:(只是需要有人指出我的错误
发布于 2019-07-17 02:08:09
如果一个指令以(*)星号前缀开头,这意味着它是angular中的结构化指令。在后台,angular将做的是将宿主元素包装在ng-template中。所以在你的例子中,整个ng容器将像下面的代码一样被包装在ng-template中,所以在你的代码中viewChild没有初始化,这就是它不能工作的原因。
<div class="frame-wrapper">
<ng-template [ngTemplateOutlet]="(windowWidth < 480)? this.realView : this.shelledView">
<ng-container>
<ng-template #realView>
realView work!!
</ng-template>
<ng-template #shelledView>
shelledView work!!
</ng-template>
</ng-container>
</ng-template>
</div>For more info check this
https://stackoverflow.com/questions/57062370
复制相似问题