Angular:如何访问父组件中的子组件模板变量?

标签 angular angular5 angular2-template

我正在尝试访问父 app.component.tsmodalconfirm.component.html#temp,但它始终为 null。

modalconfirm.component.html

<button type="button" class="btn btn-primary" (click)="openModal(template)">Open modal</button>
<br><br>
<pre class="card card-block card-header">{{message}}</pre>
<ng-template #template>
  <div class="modal-body text-center">
    <p>Do you want to confirm?</p>
    <button type="button" class="btn btn-default" (click)="confirm()" >Yes</button>
    <button type="button" class="btn btn-primary" (click)="decline()" >No</button>
  </div>
</ng-template>

app.component.ts

import { Component, TemplateRef, ViewChild, ElementRef } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';

import { BsModalService } from 'ngx-bootstrap/modal';
import { ModalcomfirmComponent } from './modalcomfirm/modalcomfirm.component';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',

   template:`
  <modalcomfirm ></modalcomfirm>

  <table>
  <tr><td><div (click)="TestChild()">1</div></td></tr>
  <tr><td><div>2</div></td></tr>
  ` 
 // styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  @ViewChild("template") inputChild: ElementRef;

  @ViewChild(ModalcomfirmComponent ) child: ModalcomfirmComponent; 
TestChild(){
  console.log(this.inputChild); //undefined

}
ngOnInit(){

}
  confirmParent(evt) {
    console.log(evt);
 }

}

最佳答案

您无法直接访问子组件的模板变量。

模板变量只能在您定义的同一个模板中引用

但是,如果您尝试从模态子组件获取结果(确认/拒绝)值,则可以通过 @Output 装饰器和 EventEmitter 来完成。

参见Angular - Component InteractionAngular - Template Syntax > Input and Output properties

另外,看看here了解智能(容器)和(演示)组件。

关于Angular:如何访问父组件中的子组件模板变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49924409/

相关文章:

angular - 单击里面的 md-tab 后,md-menu 关闭

angular - 获取对象可能是 'null' 。在 Angular 模板文件中

angular - 在 Angular 4 中,如何将 FormGroup 转换为带有查询参数的 URL?

angular - 类型 'element' .ts 上不存在属性 'Directive'

Angular 2 动态页面页眉和页脚

angular - 创建一个可以在 Angular 4 模板中使用的全局函数

javascript - Angular2 "Please add a @NgModule annotation"错误

angular - 在 angular2 中如何获取新 @Angular/router 的 RouteParams - 似乎不存在

angular - 如何在命名 socket 是未命名 socket 的子代时导航到路线

Angular 传递将数据解析为子路由