将ngIf与子组件中的值一起使用

时间:2019-11-21 11:07:25

标签: angular angular8

使用Angular 8,我有一个父组件HTML:

<div>
  <p *ngIf="Condition with value$">Message</p>
  <child></child>
</div>

我需要使用子组件上存在的ngIfP标签中使用value$

export class ChildComponent implements OnInit {

  value$: Observable<Model>;

  constructor(private service: service) { }

  ngOnInit() {

    this.value$ = // Get value using apiService

  }

}

我该怎么做?

4 个答案:

答案 0 :(得分:1)

您可以使用EventEmitter, Output

Working demo

父项:

<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;
}

演示:https://stackblitz.com/edit/angular-9mms62

答案 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)

有几种解决方法:

  1. 如前所述,您可以使用@Output();
  2. 您可以通过@ViewChild()访问子组件
  3. 您可以在Service的某些属性(例如apiValue)中写入来自API的结果。然后,您可以向(父母和孩子)注入服务并跟踪“ apiValue”的值。由于服务主要是单例-您将始终获得具有相同值的相同实例。 (这是更灵活的方式)