我正在尝试访问父 app.component.ts
中 modalconfirm.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 Interaction和 Angular - Template Syntax > Input and Output properties
另外,看看here了解智能(容器)和哑(演示)组件。
关于Angular:如何访问父组件中的子组件模板变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49924409/