首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“[ngTemplateOutet]”正在工作,但“*ngTemplateOutlet”不起作用

“[ngTemplateOutet]”正在工作,但“*ngTemplateOutlet”不起作用
EN

Stack Overflow用户
提问于 2019-07-17 01:11:40
回答 1查看 472关注 0票数 1

我试图制作一个使用ngTemplateOutlet来挑选ng-template的组件,但是我就是不明白为什么*ngTemplateOutlet在这里不能工作(但是ngTemplateOutlet可以工作)。

以下是我的代码

demo-frame.component.html:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
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:(只是需要有人指出我的错误

EN

回答 1

Stack Overflow用户

发布于 2019-07-17 02:08:09

如果一个指令以(*)星号前缀开头,这意味着它是angular中的结构化指令。在后台,angular将做的是将宿主元素包装在ng-template中。所以在你的例子中,整个ng容器将像下面的代码一样被包装在ng-template中,所以在你的代码中viewChild没有初始化,这就是它不能工作的原因。

代码语言:javascript
复制
<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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57062370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档