我试图在父#temp中访问modalconfirm.component.html的app.component.ts,但它始终为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);
}
}发布于 2018-04-19 15:33:26
不能直接访问子组件的模板变量。
模板变量只能在定义它们的同一个板中引用。
但是,如果您试图从模态子组件中获取结果(确认/下降)值,可以通过@Output装饰器和EventEmitter进行。
见角分量相互作用和Angular - Template Syntax > Input and Output properties
另外,请看一下这里,阅读有关智能(容器)和哑(表示)组件的内容。
发布于 2018-04-19 15:43:20
您好,尝试使用属性上的@Input和@Output装饰器在两个组件之间进行通信。
输出修饰器的工作方式类似于回调,以从子组件返回值,并且输入用于向子组件发送参数。
示例:
import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'child-element',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
@Input() value: number;
counter: number;
@Output() valueOutput: EventEmitter<string> =
new EventEmitter<string>();
ngOnChanges(): void {
this.counter++;
this.value= this.counter;
this.valueOutput.emit(`The value${this.value} isChanged!`);
}
}
//this.valueOutput.emit must be used when you want to return a value to the parent component
//implementation in parent html templeate
<child-element [value]='valueInParent' (valueOutput)='functionInParent()' ></child-element>functionInParent将是要发送给子组件的参数或值,而valueInParent将是父组件中的函数,它将作为子响应的回调进行调整。
https://stackoverflow.com/questions/49924409
复制相似问题