Angular2 - Template reference inside NgSwitch

时间秒杀一切 提交于 2019-12-05 19:00:32

It works if you use a template reference variable at the ngSwitchCase, this way:

<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>

Notice that, if you have:

export class SomeComponent {

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

Then ref is not yet set at when the constructor is called. Not even on init. Only after view init.

This way, with the following component:

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);
  }

}

The output is:

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

See demo plunker here.

Template reference variable should not work with structural directive. Here is explained a reason : Thomas Hilzendegen's blog

My solution is to make a template reference variable for a container tag where [ngSwitch] is used and then access to it's child using it's children property. For example

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

Also you can use forwardRef without any template references like below:

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

And access to list of components which use switch-case using ngAfterViewInit() in parent component. Or if you want to access certain one use provide: FirstComponent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!