使用Angular 8,我有一个父组件HTML:
<div>
<p *ngIf="Condition with value$">Message</p>
<child></child>
</div>
我需要使用子组件上存在的ngIf
在P
标签中使用value$
:
export class ChildComponent implements OnInit {
value$: Observable<Model>;
constructor(private service: service) { }
ngOnInit() {
this.value$ = // Get value using apiService
}
}
我该怎么做?
答案 0 :(得分:1)
您可以使用EventEmitter, Output
父项:
<div>
<p>Parent works</p>
<p *ngIf="isMessageAvailable">Message depend on child</p>
<app-child (isAvailable)="onChange($event)"></app-child>
</div>
父类文件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor() { }
ngOnInit() {
}
isMessageAvailable: boolean = true;
onChange(value) {
this.isMessageAvailable = value;
}
}
子组件
<p>
child works!
</p>
<button (click)="valueChanged()">Toogle</button>
类文件:
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
@Output() isAvailable = new EventEmitter();
childValue: boolean = true;
ngOnInit() {
}
valueChanged() {
this.childValue = !this.childValue;
this.isAvailable.emit(this.childValue);
}
}
答案 1 :(得分:1)
您可以在子组件中使用Output
变量将数据传递给父组件。
child.component.ts :
@Output() changeEvent = new EventEmitter<Model>();
ngOnInit() {
// Once you subscribe the data from the service, emit an event passing data using event emitter
this.changeEvent.emit(this.value$);
}
parent.component.html :
<div>
<p *ngIf="Condition with value$">Message</p>
<child (changeEvent)="onDataChange($event)"></child>
</div>
parent.component.ts :
// This function will be triggered when the child emits an event and the data will be available as parameter
// Use this data in your condition.
onDataChange(data){
this.data = data;
}
答案 2 :(得分:1)
您可以使用@ViewChild。 此处演示:https://angular-zucwa1.stackblitz.io
父.ts文件
import { Component, ViewChild } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
@ViewChild("childComponent", { static: false }) childComponent: any;
ngOnInit() {
}
}
父html文件
<hello name="{{ name }}"></hello>
parent component
<p *ngIf="childComponent.value$">
show according to child value
</p>
<app-child #childComponent></app-child>
答案 3 :(得分:1)
有几种解决方法: