当前位置: 首页 > 知识库问答 >
问题:

Angular2-NgSwitch内部的模板引用

梅跃
2023-03-14

我有一个NgSwitch模板。在NgSwitch中,我想获取初始化模板的模板引用。大致如下:

    <div class="container" [ngSwitch]="model.type">
        <first-component #ref *ngSwitchCase="0"></first-component>
        <second-component #ref *ngSwitchCase="1"></second-component>
        <third-component #ref *ngSwitchCase="2"></third-component>
    </div>

当单击组件中的按钮时,我想调用初始化组件(第一个/第二个/第三个)到一个方法(在所有这些 3 个组件实现的接口上定义)。问题是视图子项未定义。如果我#ref移动到容器 div,如下所示:

<div class="container" #ref [ngSwitch]="model.type">
    <first-component *ngSwitchCase="0"></first-component>
    <second-component *ngSwitchCase="1"></second-component>
    <third-component *ngSwitchCase="2"></third-component>
</div>

ViewChild(模板引用)已初始化,但我可以调用组件的方法。

如何同时使用NgSwitch指令和模板引用变量?或者另一方面,我如何从它的父组件调用初始化的组件(在一种情况下,我将#ref移动到容器div)。

共有3个答案

王俊哲
2023-03-14

您也可以在没有任何模板引用的情况下使用 forwardRef,如下所示:

@Component({
    ...
    selector: 'first-component',
    providers: [{
        provide: BaseEnumeratedComponent,
        useExisting: forwardRef(() => FirstComponent)
    }]
})

以及在父组件中使用< code > ngafterviewit()访问使用switch-case的组件列表。或者,如果您想要访问某个组件,请使用< code > provide:first component

微生毅
2023-03-14

模板引用变量不应与结构指令一起使用。下面解释一个原因:托马斯·希尔岑德根的博客

我的解决方案是为使用了[ngSwitch]的容器标记创建一个模板引用变量,然后使用它的children属性访问它的children。例如

<div [ngSwitch]="..." [class.error] = "(elem.children.item(0).className.indexOf('someClass') !== -1" #elem> 
... 
</div>
杜志
2023-03-14

如果您在ngSwitchCase中使用模板引用变量,则可以这样做:

<div class="container" [ngSwitch]="model.type">
    <first-component #ref *ngSwitchCase="0"></first-component>
    <second-component #ref *ngSwitchCase="1"></second-component>
    <third-component #ref *ngSwitchCase="2"></third-component>
</div>

请注意,如果您有:

export class SomeComponent {

  @ViewChild('ref') ref;
...

则在调用构造函数时,< code>ref尚未设置。甚至在init上也没有。仅在视图初始化后。

这样,具有以下组件:

export class AppComponent implements OnInit, AfterViewInit {
  model = {type: 0};

  @ViewChild('ref') ref;

  constructor() {
    console.log('constructor:', this.ref);
  }
  ngOnInit() {
    console.log('ngOnInit:', this.ref);
  }
  ngAfterViewInit() {
    console.log('AfterViewInit:', this.ref);
  }

}

输出为:

constructor: undefined
ngOnInit: undefined
AfterViewInit: FirstComponent {...}

请点击此处观看演示。

 类似资料:
  • 我的angular 2组件有以下模板,但它抛出了一个模板解析错误。 这是错误消息-我的

  • 打印稿enum似乎是一个自然与盎 请注意,这不同于如何cre

  • 具体查看ejs官方文档 https://github.com/mde/ejs

  • 本文向大家介绍深入理解Angular2 模板语法,包括了深入理解Angular2 模板语法的使用技巧和注意事项,需要的朋友参考一下 1. 说明 Angular2的模板用来显示组件外观,作为视图所用,用法和html语法基本一致,最简单的Angular2的模板就是一段html代码。Angular模板语法主要包括以下几个部分: l 直接绑定 l 插值表达 l 属性绑定 l 事件绑定 l 双向绑定 l 样

  • 我们自己实现了一个轻量级的模板引擎,不要问为什么不用smart之类的,因为我们认为没有必要为了一个小小的模板引擎而引入smaart这样复杂的实现。你可能会说,smart功能强大,支持各种标签,标签也是很强大,而且还可以对模板引擎进行各种"灵活"的配置... 这里我们觉得有必要说明一下: 框架的内置模板引擎基本上实现了我们日常开中所有常用的标签。 不常用的标签我们也做了巧妙的实现。 我们只提供了扩展

  • 内置模板引擎 视图的模板文件可以支持不同的解析规则,默认情况下无需手动初始化模板引擎。 可以通过下面的几种方式对模板引擎进行初始化。 配置文件 内置模板引擎的参数统一在配置目录的template.php文件中配置,例如: return [ // 模板引擎类型 支持 php think 支持扩展 'type' => 'Think', // 模板路径 '