简体   繁体   English

Angular 4:如何在ng-template中访问元素

[英]Angular 4: How to access element inside ng-template

I have a view which holds ng template for MD-Dialog. 我有一个视图,其中包含MD-Dialog的ng模板。

<ng-template #template>
  <h2 md-dialog-title>{{title}}</h2>
  <div md-dialog-content #content></div>
</ng-template>

Where I have to replace #content with a dynamic component. 我必须用动态组件替换#content。

corresponding component class is, 对应的组件类是

export class CustomDialogComponent implements OnInit, AfterViewInit {

  title: string;

  @ViewChild('content', { read: ViewContainerRef }) container;

  @ViewChild('template') template: TemplateRef<any>;

  constructor(public dialog: MdDialog,
    private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
  }

  open(component: any, options: any): void {

    this.title = options.title;
    console.log(this.container)
    const dialogRef = this.dialog.open(this.template, options);
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
    this.container.clear();
    const comp = this.container.createComponent(componentFactory);
    comp.instance.setData(options.data);

  }

  close() {
    this.dialog.closeAll();
  }

  ngAfterViewInit() {
    console.log(this.container)
  }
}

But I get undefined for this.container in method open(). 但是我在open()方法中没有为此this.container定义。 Please help. 请帮忙。

只有在初始化视图时,模板内部的模板才可访问。因此,在角度8之后,使用ViewChild时,可以使用参数{static: false}这样可以在初始化视图时使用内部模板的实例

@Viewchild('content', {static: false}) innerConttent: TemplateRef<any>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问ng-template中的元素? (角度5) - How to access element inside ng-template? ( Angular 5 ) Angular 11:如何访问 ng-template 中的原生元素 - Angular 11: How to access a native element inside ng-template Angular:在 ng 模板中访问 elementRef - Angular: Access elementRef inside an ng-template 如何在Angular 6中基于ng-template内的id引用元素? - How to reference an element based on id which is inside an ng-template in Angular 6? 如何获取动态属性的元素(DOM)(如果在内部) <ng-template > 角度的 - How to get element (DOM) of dynamic attribute ,if it's inside <ng-template > angular 如何通过父组件中的 id 访问位于 ng-template 中的子元素? - How to access a child element that is located inside ng-template by its id in a parent component? 如何引用ng-template中的元素? - How can I take reference to an element inside ng-template? 如何在Angular 2中包含没有条件的ng-template元素 - How to include an ng-template element without a condition in Angular 2 如何在 Angular 的 innerHTML 中使用 ng-template - How to use ng-template inside innerHTML in Angular 获取ng-template中的元素参考 - Get reference to element inside ng-template
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM