Angular2 - NgSwitch中的模板引用

时间:2016-07-30 13:49:13

标签: angular angular2-template ng-switch

我有一个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>

单击组件中的按钮时,我想调用初始化组件(第一个/第二个/第三个)到一个方法(在所有这三个组件实现的接口上定义)。问题是ViewChild未定义。如果我将#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 个答案:

答案 0 :(得分:3)

如果您在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;
...

然后在调用构造函数时尚未设置ref。甚至不是在init。仅在查看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 {...}

请参阅demo plunker here

答案 1 :(得分:0)

模板引用变量不应与结构指令一起使用。以下是一个原因:Thomas Hilzendegen's blog

我的解决方案是为使用[ngSwitch]的容器标签制作模板引用变量,然后使用它的子属性访问它的孩子。例如

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

答案 2 :(得分:0)

此外,您可以使用forwardRef,而无需使用任何如下模板引用:

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

并使用父组件中的ngAfterViewInit()访问使用切换大小写的组件列表。或者,如果您想访问某些内容,请使用provide: FirstComponent

相关问题